我的文件.csv:1237我需要将此文件转换为如下列表:['str-1', 'str-2', 'str-3', 'str-7']为此,我做了:import csvdata = []with open('file.csv', 'r') as f: reader = csv.reader(f) for row in reader: data.append(f"str-{row}")当我看到这行的结果时,我得到了:['str-['1']', 'str-['2']', 'str-['3']', 'str-['7']']我应该添加什么来获得我需要的数组?
3 回答
杨魅力
TA贡献1811条经验 获得超6个赞
您不需要为此使用csv:
data = []
with open('file.csv') as f:
for row in f:
data.append(f"str-{row.strip()}")
或作为列表理解:
with open('file.csv') as f:
data = [f"str-{row.strip()}" for row in f]
狐的传说
TA贡献1804条经验 获得超3个赞
import csv
data = []
with open('file.csv', 'r') as f:
reader = csv.reader(f)
for row in reader:
data.append("str-"+row[0])
print(data)
>> ['str-1', 'str-2', 'str-3', 'str-7']
ABOUTYOU
TA贡献1812条经验 获得超5个赞
您可以将代码更改为
import csv
data = []
with open('file.csv', 'r') as f:
reader = csv.reader(f)
for row in reader:
[row] = row
data.append(f"str-{row}")
添加回答
举报
0/150
提交
取消