简体   繁体   中英

Python: Removing list with repeated elements in a list of lists

I have a list of lists as follows:

seq = [[2, 5], [1, 4], [1, 2], [3, 4], [1, 5], [2, 3], [3, 5], [1, 1], [2, 4], [1, 3]]

How do I remove the list inside this list which have repeated elements ie [1, 1] ?

For this specific case:

[i for i in seq if i[0] != i[-1]]

More generally, remove sublists where all items are equivalent (kudos @ABB 8' comment):

[i for i in seq if len(set(i)) > 1]

Finally, if any replicates are found within a sublist, eg [..., [1, 2, 2]] :

import collections as ct

[i for i in seq if i and all(v == 1 for v in ct.Counter(i).values())]

Tests using the final solution:

def drop_replicates(seq):
    return [i for i in seq if i and all(v == 1 for v in ct.Counter(i).values())]


assert drop_replicates([[2, 5], [1, 1], [2, 4]]) == [[2, 5], [2, 4]]
assert drop_replicates([[2, 5], [1, 1], [2, 4], [1, 2, 2]]) == [[2, 5], [2, 4]]
assert drop_replicates([[2, 5], [1, 1], [2, 4], [1, 2, 2], []]) == [[2, 5], [2, 4]]

set(i) converts the list to a set. Sets are unordered lists without duplicates (same as mathematical sets). Following is a more generic solution, it should work with any number of elements in the child lists.

[i for i in seq if len(set(i)) == len(i)]

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