【问题标题】:Avoiding Nested Lists [duplicate]避免嵌套列表 [重复]
【发布时间】:2017-02-05 20:46:51
【问题描述】:

打印每个列表的第一个元素的最 Pythonic 方式是什么?

例如,我想要下面列表中的['apple', 'banana']

data = [['apple','airplane'],['banana','boat']]

这是我最好的尝试:

fruit = [list(fruit) for fruit in data]

[letter[0] for letter in fruit]

然而,有两个列表推导式似乎不是很pythonic

【问题讨论】:

  • 好吧,第一个列表理解并没有改变任何东西:[['apple','airplane'],['banana','boat']] == [list(fruit) for fruit in [['apple','airplane'],['banana','boat']]] 导致 True...

标签: python


【解决方案1】:

为什么不直接

fruit = [fruit[0] for fruit in data]

这让我得到了预期的输出,见下文:

>>> data = [['apple','airplane'],['banana','boat']]
>>> fruit = [fruit[0] for fruit in data]
>>> print fruit
['apple', 'banana']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-05
    • 2020-04-01
    相关资源
    最近更新 更多