如何使用python

时间:2019-03-31 13:05:33

标签: python python-3.x csv

我有两个长度可变的列表

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)

我无法分配给列表理解

如何将结果传递给writerow?

3 个答案:

答案 0 :(得分:2)

您需要使用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以排除要查找的值,因为查找速度更快(也就是说,元素更多)

答案 1 :(得分:1)

您可以尝试这样:

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

答案 2 :(得分:0)

这是完成此任务的另一种方法。此方法基于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()