了解列表推导式(和嵌套LC)的语法

时间:2018-12-27 04:26:30

标签: python python-3.x syntax list-comprehension

这有效:

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

1 个答案:

答案 0 :(得分:1)

对于列表理解,语法为

[ <something> for elem in sequence]

<something>本身可以用作列表推导。同时,对于嵌套循环(但不是嵌套列表)的理解,语法为

[<something> for elem in outerseq for elem2 in innerseq]

以同样的方式,依此类推。