【发布时间】:2019-11-13 06:42:26
【问题描述】:
我是 Python 新手,需要帮助解决一些循环问题。
我有一个名为 test1.csv 的 CSV 文件,其中有两列(Fruit 和 Fruit_Container)
Screenshot of the CSV file 这是我的代码:
import csv
def fruits():
with open('test1.csv', mode='r') as csv_file:
csv_reader = csv.DictReader(csv_file)
for row in csv_reader:
print(f'Fruits: {row["Fruit"]}')
def fruit_container():
with open('test1.csv', mode='r') as csv_file:
csv_reader = csv.DictReader(csv_file)
for row in csv_reader:
print(f'The fruits are: {row["Fruit"]} and they are placed in a {row["Fruit_Container"]}')
fruits()
fruit_container()
我得到的结果如下:
Fruits: Apple
Fruits: Banana
Fruits: Orange
The fruits are: Apple and they are placed in a Crate
The fruits are: Banana and they are placed in a Crate
The fruits are: Orange and they are placed in a Crate
但我想要的结果如下:
Fruits: Apple
Fruits: Banana
Fruits: Orange
The fruits are:
Apple and they are placed in a Crate
Banana and they are placed in a Crate
Orange and they are placed in a Crate
我怎样才能实现这个输出?
问候 丹尼斯
【问题讨论】:
-
将“The fruits are:”(只有那些词!)的打印移动到循环之前,它只会打印一次。
-
在fruit_container() 函数中,“水果是:”应该在循环之外