python - 从字符串列表中删除多余的组成字符串
问题描述
我看到昨天发布的一个问题,关于这样的列表如何:
my_list = ["lol hi there", "hi", "i like", "i like apples", "goodbye"]
可以转换为:
my_list = ["lol hi there", "i like apples", "goodbye"]
其中字符串喜欢"hi"
和"i like"
从 中删除my_list
,因为"hi"
和分别"i like"
在字符串"lol hi there"
和中找到"i like apples"
。它们被从列表中删除纯粹是因为它们出现在列表中的任何其他字符串中,而不管列表中的索引或字符串中的位置。
另一个例子是:
my_list1 = ["hello", "he", "go", "goodbye", "good", ]
将转换为:
my_list1 = ["hello", "goodbye"]
由于"he"
in "hello"
, and "go"
, 以及"good"
, in的重复出现"goodbye"
。
我为此尝试使用以下方法:
import re
my_list = ["lol hi there", "hi", "i like", "i like apples", "goodbye"]
for x in my_list:
for y in my_list:
if x != y:
if len(x) < len(y):
if re.search(x, y):
my_list.pop(my_list.index(x))
else:
if re.search(y, x):
my_list.pop(my_list.index(y))
print(my_list)
这让我得到了我想要的。用户已经删除了他们的问题,但我想知道一种更简洁的方法来解决这个问题。有人可以帮帮我吗?
解决方案
如果您不关心使用正则表达式,则可以使用in
运算符。
my_list = ["lol hi there", "hi", "i like", "i like apples", "goodbye"]
filtered_list = []
for i,si in enumerate(my_list):
# search each element against every other element in the list, j != i ensures it doesnt compare to self.
inlist = any( [ si in xi for j, xi in enumerate(my_list) if j != i] )
if not inlist:
filtered_list.append( si )
print( filtered_list )
或者,如果您更喜欢一行:
filtered_list = [ si for i, si in enumerate( my_list ) if not any( [si in sii for j, sii in enumerate(my_list) if j != i] )]
print( filtered_list )
推荐阅读
- clojurescript - 无论调整大小,如何使图像上的文本覆盖稳定?
- datetime - 如何使用 JIRA 智能值获取自纪元以来的毫秒数?
- javascript - 如何为 Bootstrap 4 滑动下拉菜单设置动画?
- performance-testing - 将响应代码和错误文本从加特林写入石墨 influxDB
- node.js - 使用 adminDeleteUser 时出现“AccessDeniedException”
- python - python的无限循环
- python - Smartsheet API - 在同一工作表中复制和粘贴行
- json - 在 TypeScript 中导入远程 JSON 文件时出现“找不到模块”错误
- r - 绘制百分比而不是密度
- css - 为什么我的小部件不在屏幕中央?