【问题标题】:python substitute an element to a list in list comprehensionpython将元素替换为列表理解中的列表
【发布时间】:2020-07-02 01:45:29
【问题描述】:

我正在尝试使用列表推导来使列表准备好输出到 csv 文件。

当我写作时

record[:] = [[', '.join(row)] if element == int(row[4]) else element for element in records]

它输出我想要的。但是由于 csv 输出格式需要在列表中包含列表,因此我需要将 else 部分中未更改的“元素”替换为列表。 因此,我尝试了

record[:] = [[', '.join(row)] if element == int(row[4]) else [element] for element in records]

但这不起作用。此命令无法正确识别和替换。发现被第一种方法替换的一些元素没有被这种方法替换,这很奇怪。 因此,我想知道这里发生了什么。

谢谢。

【问题讨论】:

  • 这里有一个错字(额外的括号):', '.join(row))
  • @revliscano 已编辑,谢谢
  • 能否提供rowrecords的内容示例?
  • 我无法重现您的问题。抛出了什么错误?

标签: python list csv list-comprehension


【解决方案1】:

当我尝试你的代码时效果很好:

row = ['1','2','3','4','5']
records = [6,7,8,9,0,10,5,11,12]

res = [[', '.join(row)] if element == int(row[4]) else element for element in records]
res = [[', '.join(row)] if element == int(row[4]) else [element] for element in records]

也许你应该提供recordsrowrecord的样本

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-25
    相关资源
    最近更新 更多