上周刚开始使用Python,我真的很喜欢它!但是,我一直试图找出如何通过循环读取csv文件的方法。浏览https://www.tutorialspoint.com/python/python_for_loop.htm提供的示例:
fruits = ['banana', 'apple', 'mango']
for fruit in fruits:
print('Current fruit :', fruit)
如何正确更换 ['香蕉','苹果','芒果'] csv文件的打印方式与上图所示相同?
import csv
with open(r'C:\Documents\Fruits.csv', 'r') as f:
reader = csv.reader(f)
fruit_list = list(reader)
fruits = [fruit_list]
for fruit in fruits:
print('Current fruit :', fruit)
但是它打印:
当前水果:[['香蕉'],['苹果'],['芒果']]
谢谢
答案 0 :(得分:1)
fruit_list
是一个列表列表。当您执行fruits = [fruit_list]
时,您将fruit_list
从[['banana'], ['apple'], ['mango']]
转换为[[['banana'], ['apple'], ['mango']]]
。这是列表列表的列表。相反,您想将列表列表转换为简单列表。可以做到:
fruits = [i for I in fruit_list for i in I]
for fruit in fruits:
print('Current fruit :', fruit)
祝您学习Python顺利!