with open('LBP_for_paper.csv','r') as csvDataFile:
datarows = csv.reader(csvDataFile, delimiter=',', quotechar='|')
nofinding=[]
rawrow=[]
for row in datarows:
if row[1]=='No Finding' and row[2]=='1':
rawrow = list((row[0]+","+row[1]+","+row[2]+","+row[17]+","+row[18]))
nofinding.append(rawrow)
print(nofinding[:2])
我正在从csv文件读取数据行,并希望基于某些列创建自定义的嵌套列表。我想要
list((row [0] +“,” + row [1] +“,” + row [2] +“,” + row [17] +“,” + row [18]))>
应返回
之类的列表['00030805_000.png,没有发现,1,34777,69373']
存储在rawrow中,然后追加到更大的列表,即nofinding,但我得到的输出为
[[''0','0','0','3','0','8','0','5','','0','0' ,“ 0”,“。”, 'p','n','g',',','N','o',','F','i','n','d','i','n' , 'G', ',','1',',','3','4','7','7','7',',','6','9','3','7 ','3'], ['0','0','0','3','0','8','0','4','','0','0','0 ','。','p', 'n','g',',','N','o','','F','i','n','d','i','n','g' ,',', '1',',','3','5','4','0','5',',','6','3','0','8','8 ']]
所需的输出
[['00030805_000.png,没有发现,1,34777,69373'],['00030804_000.png,没有 结果,1,35405,63088']]
谢谢
答案 0 :(得分:0)
您的问题是rawrow = list((row[0]+","+row[1]+","+row[2]+","+row[17]+","+row[18]))
正在将字符串变成字符列表
如果要将其保留为逗号分隔的字符串,请将该行替换为以下内容:
rawrow = row[0]+","+row[1]+","+row[2]+","+row[17]+","+row[18]
或更简洁:
rawrow = ",".join([row[row_index] for row_index in [0, 1, 2, 17, 18]])
我很好奇你为什么要这么做
[ ['00030805_000.png,No Finding,1,34777,69373'], ['00030804_000.png,No Finding,1,35405,63088'] ]
代替此:
[ ['00030805_000.png','No Finding',1,34777,69373], ['00030804_000.png','No Finding',1,35405,63088] ]
您可以通过以下方法实现:
rawrow = []
for row_index in [0, 1, 2, 17, 18]:
rawrow.append(row[row_index].split(","))
或一行:
rawrow = [row[row_index].split(",") for row_index in [0, 1, 2, 17, 18]]
此外,您的整个代码可以按以下方式合并:
with open('LBP_for_paper.csv','r') as csvDataFile:
datarows = csv.reader(csvDataFile, delimiter=',', quotechar='|')
nofinding = [",".join([row[row_index] for row_index in [0, 1, 2, 17, 18]]) for row in datarows if row[1]=='No Finding' and row[2]=='1']
print(nofinding[:2])
答案 1 :(得分:0)
with open('LBP_for_paper.csv','r') as csvDataFile:
datarows = csv.reader(csvDataFile, delimiter=',', quotechar='|')
rawrow = []
nofindings=[]
for row in datarows:
if row[1]=='No Finding' and row[2]=='1':
rawrow = [''.join(row[row_index]) for row_index in [0, 1, 2, 17, 18] ]
nofindings.append(rawrow)
print(nofindings[:3])
解决了我的问题。