了解列表理解(和嵌套LC)的语法 [英] Understanding the syntax of list comprehensions (and nested LCs)
本文介绍了了解列表理解(和嵌套LC)的语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这有效:
allDasTickets = ["9255955", "9255958", "9255960", "9255977"]
[[j for j in allDasTickets if x != j] for x in allDasTickets]
['9255958', '9255960', '9255977']
['9255955', '9255958', '9255977']
['9255958', '9255960', '9255977']
['9255955', '9255958', '9255960']
但这不是:
allDasTickets = ["9255955", "9255958", "9255960", "9255977"]
[for x in allDasTickets [j for j in allDasTickets if x != j]]
File "<stdin>", line 1
[for x in allDasTickets [j for j in allDasTickets if x != j]]
^
推荐答案
对于列表理解,语法为
[ <something> for elem in sequence]
<something>
本身可以是列表推导.同时,对于嵌套循环(但不是嵌套列表)的理解,语法为
Where <something>
can itself be a list comprehension. Meanwhile, for nested loop (but not nested lists) comprehensions, the syntax is
[<something> for elem in outerseq for elem2 in innerseq]
以同样的方式,依此类推.
In the same way, and so on.
这篇关于了解列表理解(和嵌套LC)的语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文