繁体   English   中英

如何使用python将列表推导结果传递给csv

[英]How can I pass a list comprehension results into a csv using python

我有两个可变长度的列表

list1 = ['x1','x2','x3','x4','x5']

list2 = ['x5','x4']

我尝试以下方法来找到缺少的元素

*[item for item in list1 if item not in list2], sep='\n'

但如果我这样做

item = *[item for item in skuslist if item not in retaillist], sep='\n'
csvwriter.writerow(item)

我得到不能分配列表理解

我怎样才能将结果传递给作家?

您需要使用writerows每行编写一个项目,并将每个项目放在1个元素的列表中:

list1 = ['x1','x2','x3','x4','x5']

list2 = {'x5','x4'}

import csv

with open("test.csv","w",newline="") as f:
    cw = csv.writer(f)
    cw.writerows([x] for x in list1 if x not in list2)

细节:为要排除的值创建一个set ,因为查找更快(即,对于更多元素)

你可以尝试这样:

import csv

list1 = ['x1','x2','x3','x4','x5']
list2 = ['x5','x4']

with open('output.csv', 'w') as f:
    writer = csv.writer(f, delimiter='\n', quoting=csv.QUOTE_NONE)
    writer.writerow([item for item in list1 if item not in list2])

这是完成此任务的另一种方法。 此方法基于list1和list2之间的差异创建一个集合。 代码还会按顺序将值写入CSV文件。

import csv

list1 = ['x1','x2','x3','x4','x5']
list2 = ['x5','x4']

# Obtain the differences between list1 and list2
list_difference = (list(set(list1).difference(list2)))

# Uses list comprehension to write the values to a CSV file.
# Uses sorted to write the values in order to the CSV file.
with open('output.csv', 'w') as outfile:
   csv_writer = csv.writer(outfile)
   csv_writer.writerows([[x] for x in sorted(list_difference)])
   outfile.close()

你也可以这样做。

import csv

list1 = ['x1','x2','x3','x4','x5']
list2 = ['x5','x4']

# Obtain the differences between list1 and list2.
# Uses list comprehension to write the values to a CSV file.
# Uses sorted to write the values in order to the CSV file.
with open('output.csv', 'w') as outfile:
   csv_writer = csv.writer(outfile)
   csv_writer.writerows([[x] for x in sorted(list(set(list1).difference(list2)))])
   outfile.close()

暂无
暂无

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

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