Understanding nested list comprehension syntax in Python

2022/5/24 1:22:50

本文主要是介绍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)]


这篇关于Understanding nested list comprehension syntax in Python的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程