编程语言
首页 > 编程语言> > Understanding nested list comprehension syntax in Python

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

标签:word,Python,list,nested,comprehensions,words,syntax
来源: https://www.cnblogs.com/clamber/p/16300750.html