【问题标题】:Understanding the syntax of list comprehensions (and nested LCs)理解列表推导(和嵌套 LC)的语法
【发布时间】:2018-12-27 04:26:30
【问题描述】:

这行得通:

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

【问题讨论】:

  • 我不明白您为什么会期望它起作用。语法只是没有这样定义。这是[a for b in c],而不是[for b in c a]
  • @user2357112 我不认为我期望它会起作用,只是我一直在搞砸它并想知道为什么。如果我有一个搞砸的原因,我会记得更清楚。
  • @coldspeed 哇,我很荣幸得到你的支持(如果是你)
  • 我总是赞成我回答的问题(因为这意味着这是一个值得回答的问题,至少在我看来):-)

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


【解决方案1】:

对于列表推导,语法是

[ <something> for elem in sequence]

&lt;something&gt; 本身可以是一个列表理解。同时,对于嵌套循环(但不是嵌套列表)推导式,语法是

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-15
    • 2012-08-09
    • 1970-01-01
    • 2019-03-03
    • 1970-01-01
    • 1970-01-01
    • 2011-12-24
    • 1970-01-01
    相关资源
    最近更新 更多