我的代码:
import os
import csv
mylist = []
data = os.getcwd() + '/' + 'filename.csv'
with open(data, 'r') as file:
read = csv.reader(file)
mylist = list(read)
print(mylist)
mylist.append('hello')
print(mylist)
打印时,输出显示:
[['25', '50', '33', '24', '214', '1587']]
[['25', '50', '33', '24', '214', '1587'], 'hello']
导入CSV数据是作为列表中的列表加载的。但我需要在一个列表中添加相同的值,以便稍后在同一列表中添加一些值,如"hello"。
示例:(我需要相同的)
['25', '50', '33', '24', '214', '1587', 'hello']
请提供修复:
从itertools
:使用chain.from_iterables
import itertools
mylist = [['1', '2'], ['3', '4'], ['5', '6'], ['7', '8']]
mylist = list(itertools.chain.from_iterable(mylist))
mylist.append('hello')
>>> mylist
['1', '2', '3', '4', '5', '6', '7', '8', 'hello']
追加前后输出:
['25', '50', '33', '24', '214', '1587']
['25', '50', '33', '24', '214', '1587', 'hello']
代码:
import os
import csv
mylist = []
data = os.getcwd() + '/' + 'filename.csv'
with open(data, 'r') as file:
read = csv.reader(file)
mylist = list(read)
print(mylist)
y=[]
for x in range(len(mylist)):
y.append(mylist[x])
mylist = y
mylist.append('hello')
print(mylist)
您可以使用:
import os
import csv
mylist = []
data = os.getcwd() + '/' + 'filename.csv'
with open(data, 'r') as file:
read = csv.reader(file)
mylist = list(read)
print(mylist)
mylist2 = mylist[0]
mylist2.append('hello')
print(mylist2)
其中mylist2 = mylist[0]
假设您读取csv文件的列表为1级嵌套列表。然后,您可以将新值附加到新列表mylist2
中