Understanding nested list comprehension syntax in Python

Success!

One final, more complex example: Let’s say that we have a list of lists of words and we want to get a list of all the letters of these words along with the index of the list they belong to but only for words with more than two characters. Using the same for-loop syntax for the nested list comprehensions we’ll get:

https://spapas.github.io/2016/04/27/python-nested-list-comprehensions/

strings = [ ['foo', 'bar'], ['baz', 'taz'], ['w', 'koko'] ]
[(letter, idx) for idx, lst in enumerate(strings) for word in lst if len(word)>2 for letter in word]

>>>[('f', 0), ('o', 0), ('o', 0), ('b', 0), ('a', 0), ('r', 0), ('b', 1), ('a', 1), ('z', 1), ('t', 1), ('a', 1), ('z', 1), ('k', 2), ('o', 2), ('k', 2), ('o', 2)]
posted @ 2022-05-23 12:15  渐远的围城  阅读(18)  评论(0编辑  收藏  举报