简体   繁体   中英

list comprehension for list of list in Python

I have a list of lists and I want to find the indices where '//' occurs. I know how to do it if I use nested loops but, I want to use list comprehension. My list is:

ex = [['foo', 'faa'], ['//', 'sd'], ['foo', 'kaa'], ['side', 'haha', 'blue'], ['//', 'sd']]

How can I use list comprehension here to find indices where '//' occurs? What I've done so far is:

indices = [idx for idx, lst in enumerate(ex)]

This gives me the indices of my lists in the list. But I don't know how to use these to find indices for '//' using list comprehension.

For the above ex example, the expected output is

[1, 4]

eg the indices for the nested lists containing '//' , which are ex[1] and ex[4] .

Nested list comprehensions are only needed when the output contains nested lists. List comprehensions produce lists, nested list comprehensions produce a list of lists. You are only producing indices here, for each nested list that passes a test.

If all you want to do is test for the '//' string being in the nested list, just use a filtering if expression in the list comprehension:

indices = [idx for idx, lst in enumerate(ex) if '//' in lst]

If you need to know if '//' is a substring of any of the values, then it's still a filter test, but with the any() function and a generator expression:

indices = [idx for idx, lst in enumerate(ex) if any('//' in el for el in lst)]

The any() function iterates over the generator expression one step at a time, and the moment a result produced is a true value, it'll stop iterating and return True . This makes for a very efficient method of testing your nested lists.

This comprehension will do:

>>> indices = [idx for idx, lst in enumerate(ex) if "//" in lst]
>>> indices
[1, 4]

If you want to check if "//" is present inside any strings in the lists:

>>> indices = [idx for idx, lst in enumerate(ex) if any("//" in x for x in lst)]

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