我有这个代码,我合并了2个文件:
f1 = open('file.csv', 'r')
f2 = open(file2.csv', 'r')
f3 = open('results.csv', 'w')
c1 = csv.reader(f1)
c2 = csv.reader(f2)
c3 = csv.writer(f3)
file2 = list(c2)
for file1_row in c1:
row = 1
found = False
results_row = file1_row
for file2_row in file2:
x = file2_row[1:]
if file1_row[0] == file2_row[0]:
results_row.append(x)
found = True
break
row += 1
if not found:
results_row.append('Not found')
c3.writerow(results_row)
f1.close()
f2.close()
f3.close()
输出是:
455, E+13, 5.05, 12, 378, BDAP, BT28, I, NSW, ['0.000000', '20140723', '20170803']
484, E+13, 5.05, 2.0, 204, LAP, 3G2, A, NSW, ['2.980000', '20150714', '20180217']
如何从添加的字段中删除“[]”和“'”? 我希望输出为:
455, E+13, 5.05, 12, 378, BDAP, BT28, I, NSW, 0.000000, 20140723, 20170803
484, E+13, 5.05, 2.0, 204, LAP, 3G2, A, NSW, 2.980000, 20150714, 20180217
答案 0 :(得分:2)
您要将列表附加到列表中。你真正想做的是extend
第一个列表与第二个列表中的每个项目:
>>> c1 = [1, 2, 3]
>>> c2 = ['a', 'b']
>>> c1.append(c2)
>>> c1
[1, 2, 3, ['a', 'b']]
>>> c1 = [1, 2, 3]
>>> c1.extend(c2)
>>> c1
[1, 2, 3, 'a', 'b']
答案 1 :(得分:1)
正如@JoshSmeaton所说,使用extend
而不是append
可以实现。
我只是在你已经获得嵌套列表的情况下发布另一种方法,并且不能改变列表添加新元素的方式。
flatList = []
def unfold(X):
for x in X:
if isinstance(x, list):
unfold(x)
else:
flatList.append(x)
输入:
nestedList = [1, 2, [3, 4, 5]]
unfold(nestedList)
print(flatList)
输出:
[1, 2, 3, 4, 5]