迭代列表中没有冗余的元素;蟒蛇

时间:2016-03-14 10:02:30

标签: python list-comprehension

我有一个搜索字符串,例如

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]]

现在我想要的是将列表添加到sample列表中,如果其中一个元素位于string

如果我只是遍历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]]

但是不能理解如何在循环中完成它。

3 个答案:

答案 0 :(得分:4)

另一个答案根据您的解决方案提出了正确的方法,作为一种更加pythonic的方式,您可以在string中保留set并在列表理解中使用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]]

答案 1 :(得分: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)

答案 2 :(得分:2)

您可以使用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]]