我正在编写一些代码,如果元组不包含单独列表中的所有字符串,则需要从元组列表中删除一个元组。我已经让它在for循环中工作,但我正在努力提高代码的效率。举个例子,如果我有
list_of_tups = [('R', 'S', 'T'), ('A', 'B'), ('L', 'N', 'E'), ('R', 'S', 'T', 'L'), ('R', 'S', 'T', 'L', 'N', 'E')]
needed_strings = ['R', 'S', 'T']
我想在我的列表中保留以下元组:
[('R', 'S', 'T'), ('R', 'S', 'T', 'L'), ('R', 'S', 'T', 'L', 'N', 'E')]
这在以下for-循环中工作:
for s in needed_strings:
for tup in list_of_tups:
if s not in tup:
list_of_tups.remove(tup)
然而,我希望通过列表理解来完成这一任务。我尝试这样做会产生一个元组列表,其中任何字符串,而不是所有字符串,都出现在元组中。
发布于 2019-06-17 08:32:59
您可以在嵌套的理解中使用all
:
list_of_tups = [('R', 'S', 'T'), ('A', 'B'), ('L', 'N', 'E'), ('R', 'S', 'T', 'L'), ('R', 'S', 'T', 'L', 'N', 'E')]
needed_strings = ['R', 'S', 'T']
[t for t in list_of_tups if all(c in t for c in needed_strings)]
结果
[('R', 'S', 'T'), ('R', 'S', 'T', 'L'), ('R', 'S', 'T', 'L', 'N', 'E')]
只要列表中包含可理解的项目,另一种可能更容易阅读的方法就是让needed_strings
成为set
。那么您可以使用issubset()
list_of_tups = [('R', 'S', 'T'), ('A', 'B'), ('L', 'N', 'E'), ('R', 'S', 'T', 'L'), ('R', 'S', 'T', 'L', 'N', 'E')]
needed_strings = set(['R', 'S', 'T'])
[t for t in list_of_tups if needed_strings.issubset(t)]
发布于 2019-06-17 08:48:02
你可以试试这个,
list_of_tups = [('R', 'S', 'T'), ('A', 'B'), ('L', 'N', 'E'), ('R', 'S', 'T', 'L'), ('R', 'S', 'T', 'L', 'N', 'E')]
needed_strings =['R', 'S', 'T']
y=[x for x in list_of_tups if set(needed_strings).issubset(set(x))]
print(y)
产出:
[('R', 'S', 'T'), ('R', 'S', 'T', 'L'), ('R', 'S', 'T', 'L', 'N', 'E')]
发布于 2019-06-17 08:53:00
list_of_tups = [
('R', 'S', 'T'),
('A', 'B'),
('L', 'N', 'E'),
('R', 'S', 'T', 'L'),
('R', 'S', 'T', 'L', 'N', 'E')
]
needed_chars = {'R', 'S', 'T'} # using a set to speed up membership operations
# Append the tuple element from the list of tuples if the condition is met
list_of_tups_removed = [
tup
for tup in list_of_tups
if any(c in needed_chars for c in tup) # if any of the characters are present in needed_chars
]
print(list_of_tups_removed)
输出:
[('R', 'S', 'T'), ('R', 'S', 'T', 'L'), ('R', 'S', 'T', 'L', 'N', 'E')]
列表理解语法只能用于创建新列表。它不能用于从现有列表中删除元素。
https://stackoverflow.com/questions/56635398
复制相似问题