简体   繁体   English

python 将元素替换为列表理解中的列表

[英]python substitute an element to a list in list comprehension

I am trying to use a list comprehension to make a list ready for output to csv file.我正在尝试使用列表理解来为 output 到 csv 文件准备一个列表。

When I write当我写

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

It outputs what I want.它输出我想要的。 But since csv output format needs to have lists in a list, I need to substitute the unchanged 'element' in else part to a list.但是由于 csv output 格式需要在列表中有列表,我需要将其他部分中未更改的“元素”替换为列表。 I thus, tried因此,我尝试了

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

But this does not work.但这不起作用。 This command cannot recognise and substitute correctly.此命令无法正确识别和替换。 Some elements found being substituted by the first method are not substituted by this method, which is quite odd.发现被第一种方法替换的一些元素没有被这种方法替换,这很奇怪。 I thus, was wondering what has happened here.因此,我想知道这里发生了什么。

Thanks.谢谢。

It worked well when I tried ur code:当我尝试你的代码时效果很好:

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]

Maybe u should give a sample of records , row and record也许你应该给一个recordsrowrecord的样本

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM