简体   繁体   中英

excluding lists that have more than one x

I have a bunch of lists that look something like this:

my_list = [x, y, z, x, z, w]

I want to exclude lists that have more than one 'x', however one 'x' is allowed, as well as repeats of other letters.

I'm not quite sure where to start with this...

You can find the number of list items equal to x by

my_list.count(x)

To filter a list of lists for only the lists that contain up to one x , use

[lst for lst in list_of_lists if lst.count(x) <= 1]

使用collections.Counter来计算'x'的数量。

The count() method will return the number of times a certain element appeared in the list, eg:

list.count(x)

So you can do something like

if list.count(x) <= 1:

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