简体   繁体   English

对列表元素进行迭代而没有冗余; 蟒蛇

[英]Iteration over elements of a list without redundancy; Python

I have a search string eg 我有一个搜索字符串,例如

string = [1,2,3]

and a sample 和一个样本

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

Now what I want is to append the lists in the sample list of lists if one of their elements is in string 现在,我想要的是如果列表中的元素之一在string中,则将列表追加到列表的sample列表中

If I simply iterate over every element of the list in sample I get a lot of redundancy: 如果我只是简单地遍历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

What I need is to have the lists appended only once depending on whether their element is is string or not. 我需要的是仅将列表附加一次,具体取决于其元素是否为string Eg, 例如,

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

But can't understand how to do it in a loop. 但是无法理解如何循环执行。

Another answer suggested a correct way based on your solution, as a more pythonic way you can preserve the string in a set and use set.intersection method within a list comprehension in order to get the accepted items: 另一个答案根据您的解决方案提出了一种正确的方法,这是一种更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]]

Just check if it was already inserted in accepted or rejected, not the best performance: 只需检查它是否已插入已接受或拒绝中,而不是最佳性能即可:

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)

You can use a Python set to quickly determine if any of the elements in the search are present in each sample as follows: 您可以使用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             

This would display: 这将显示:

[[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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM