如何在阅读csv

时间:2018-06-15 13:38:50

标签: python string csv

with open("D:\Vocabulary.csv","r") as CSV_file:
csv_reader=csv.reader(CSV_file)
for line in csv_reader:
    print(line)

我读了一个csv文件(在文件中我只有一列包含所有词汇表)并打印包含多个括号的结果,如下所示:

["apple"],["school"],["big"],[list]

那我该如何获得

["apple","school","big","list"]?

5 个答案:

答案 0 :(得分:1)

你想要这个吗?

my_list = [["apple"],["school"],["big"]]
expected_list = [x for b in my_list for x in b] #list comprehension
print(expected_list)

答案 1 :(得分:0)

将您的值放在列表中,以便更容易迭代它们;

values = [["apple"],["school"],["big"],["list"]]
new_list = []
for v in values:
  new_list.append(v[0])
print(new_list)

希望这有帮助。

答案 2 :(得分:0)

tupl = ["apple"],["school"],["big"],["list"]

lst = [x[0] for x in tulp]
print(lst)

<强> 输出

['apple', 'school', 'big', 'list']

答案 3 :(得分:0)

您似乎需要list.extend

<强>实施例

import csv
result = []
with open("D:\Vocabulary.csv","r") as CSV_file:
    csv_reader=csv.reader(CSV_file)
    for line in csv_reader:
        result.extend(line)
print( result )

答案 4 :(得分:0)

看起来你有字符串需要转换为列表。 Python eval将为您完成。

csv = '["apple"],["school"],["big"],["list"]'
output = [x[0] for x in eval(csv)] #['apple', 'school', 'big', 'list']