这是我的代码:
names = []
filename = "names.csv"
filedir = ""
csv_file = os.path.join(filedir, filename)
with open(csv_file) as file:
reader = csv.reader(file)
for row in reader:
name = row
names.append(name)
print(names)
这是我得到的输出:
[['hello'], ['hello'], ['one'], ['two'], ['three']]
我想要的输出是:
['hello', 'hello', 'one', 'two', 'three']
我不知道为什么会这样。如果可以的话,请先谢谢。
答案 0 :(得分:2)
最简单的方法:
for row in reader:
[name] = row
names.append(name)
print names
答案 1 :(得分:1)
您可以在姓名上执行此操作
x=[['hello'], ['hello'], ['one'], ['two'], ['three']]
t = []
for i in x:
for j in i:
t.append(j)
或者您可以根据自己的情况执行以下操作:
names = []
for row in reader:
names.append(row[0])
答案 2 :(得分:0)
使用默认列表:
new_names = [name for names_list in names for name in names_list]
使用numpy:
import numpy as np
new_names = np.array(names).flatten()
答案 3 :(得分:0)
之所以发生这种情况,是因为csv.reader
以列表的形式遍历行。
看来您的csv的每一行中只有一个元素?
如果确实如此,并且总是如此,那么您可以做两件事:
1)
with open(csv_file) as file:
reader = csv.reader(file)
for row in reader:
name = row
names.append(name[0])
2)
with open(csv_file) as file:
reader = csv.reader(file)
for row in reader:
name = row
names.extend(name)
扩展将迭代器解压缩到列表中。
答案 4 :(得分:0)
单行解决方案:
names = [['hello'], ['hello'], ['one'], ['two'], ['three']]
list(map(lambda x: x[0], names))