[英]Iteration over elements of a list without redundancy; Python
我有一个搜索字符串,例如
string = [1,2,3]
和一个样本
sample = [[1,5,5,5,5,5],[2,5,5,5,5,5],[3,5,5,5,2],[4,5,5,5,5,5],[5,5,5,5,5]]
现在,我想要的是如果列表中的元素之一在string
中,则将列表追加到列表的sample
列表中
如果我只是简单地遍历sample
列表的每个元素,那么我会得到很多冗余:
accepted = []
rejected = []
for list in sample:
for e in list:
if e in string:
accepted.append(list)
else:
rejected.append(list)
accepted
Out: [[1, 5, 5, 5, 5, 5], [2, 5, 5, 5, 5, 5], [3, 5, 5, 5, 2], [3, 5, 5, 5, 2]]
len(rejected)
Out: 23
我需要的是仅将列表附加一次,具体取决于其元素是否为string
。 例如,
accepted
Out: [[1, 5, 5, 5, 5, 5], [2, 5, 5, 5, 5, 5], [3, 5, 5, 5, 2]]
rejected
Out: [[4,5,5,5,5,5],[5,5,5,5,5]]
但是无法理解如何循环执行。
另一个答案根据您的解决方案提出了一种正确的方法,这是一种更Python化的方法,您可以将string
保留在set
并在列表set.intersection
使用set.intersection
方法以获取可接受的项目:
>>> string = {1,2,3}
>>> [i for i in sample if string.intersection(i)]
[[1, 5, 5, 5, 5, 5], [2, 5, 5, 5, 5, 5], [3, 5, 5, 5, 2]]
只需检查它是否已插入已接受或拒绝中,而不是最佳性能即可:
for list in sample:
if list not in accepted and list not in rejected:
for e in list:
if e in string:
accepted.append(list)
break
elif list not in rejected:
rejected.append(list)
您可以使用Python集快速确定每个样本中是否存在搜索中的任何元素,如下所示:
search = set([1, 2, 3])
sample = [[1,5,5,5,5,5],[2,5,5,5,5,5],[3,5,5,5,2],[4,5,5,5,5,5],[5,5,5,5,5]]
accepted = []
rejected = []
for x in sample:
if set(x) & search:
accepted.append(x)
else:
rejected.append(x)
print accepted
print rejected
这将显示:
[[1, 5, 5, 5, 5, 5], [2, 5, 5, 5, 5, 5], [3, 5, 5, 5, 2]]
[[4, 5, 5, 5, 5, 5], [5, 5, 5, 5, 5]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.