gpt4 book ai didi

python - 从 CSV 文件中获取值列表

转载 作者:太空宇宙 更新时间:2023-11-04 07:59:55 24 4
gpt4 key购买 nike

我得到了一个包含订单列表的 csv 文件,如下所示:

CUSTOMER_CODE,CUSTOMER_NAME,NAME,PRODUCT
1044, C1, Name1, Arduino,
1044, C1, Name1, ESP8266,
1048, C2, Name1, Arduino Uno,
1042, C3, Name1, ESP32,
1049, C4, Name1, Arduino Mega,
1042, C3, Name1, Nexus 4,

现在我只想提取客户代码列表[1042, 1044 ,1048 ,1049]

不是

[1042, 1044 ,1044,1044,1044,1044,1044,1044,1048,1048,1048,1048,1048,1048,1048,1049 等]

#!/usr/bin/python
import MySQLdb, csv
CUSTOMER_CODES = []

with open('Customers.csv','r') as csvfile:
reader = csv.DictReader(csvfile)

for row in reader:
if len(CUSTOMER_CODES) == 0:
#adding 1st value
CUSTOMER_CODES.append(int(row['CUSTOMER_CODE']))
for i in range(0,len(CUSTOMER_CODES)):
#check each value of table
print CUSTOMER_CODES
if CUSTOMER_CODES[i] == int(row['CUSTOMER_CODE']):
print "Code is already here "+ str(row['CUSTOMER_CODE'])
else:
CUSTOMER_CODES.append(int(row['CUSTOMER_CODE']))

而不是像这样的输出:

[1044, 1045, 1047....]

我有这个:

[1044, 1045, 1045, 1045, 1045, 1045, 1045, 1045, 1045, 1045, 1045, 1045, 1045, 1045, 1045, 1045, 1045, 1045, 1045, 1045, 1045, 1045, 1047, 1047, 1047, 1047, 1047, 1047, 1047, 1047, 1047,

最佳答案

只需使用 set 而不是 list:

#!/usr/bin/python
import MySQLdb, csv
CUSTOMER_CODES = set()

with open('Customers.csv','r') as csvfile:
reader = csv.DictReader(csvfile)

for row in reader:
CUSTOMER_CODES.add(int(row['CUSTOMER_CODE']))

或者使用集合理解(假设 Python 2.6+):

#!/usr/bin/python
import MySQLdb, csv

with open('Customers.csv','r') as csvfile:
reader = csv.DictReader(csvfile)
CUSTOMER_CODES = {int(row['CUSTOMER_CODE']) for row in reader}


如果您想要排序列表,请添加 CUSTOMER_CODES = sorted(CUSTOMER_CODES)

关于python - 从 CSV 文件中获取值列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41958598/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com