简体   繁体   中英

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

If I simply iterate over every element of the list in sample I get a lot of redundancy:

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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