我知道外部for循环应该运行一次,而内部for循环应该完全运行,但是一旦内部for循环完成,外部for循环就不会再继续执行文件中的第二行。怎么了?
import csv
import pprint
import sys
team = []
with open("sample_runner_data.csv", "r") as sample_csv:
sample_csv = csv.DictReader(sample_csv)
for lines in sample_csv:
theLine = lines["team"]
for line in sample_csv:
if(theLine == line["team"]):
print(line["team"])
team.append(line["time"])
'''
The output of the above print(line["team]) statement is as follows. Abra is simply the team
name and there are 7 teams named Abra.
Abra
Abra
Abra
Abra
Abra
Abra
Abra
'''
答案 0 :(得分:0)
您使用的是相同的基础sample_csv
文件,这意味着一旦迭代遍历完,所有后续迭代器将结束。读入数据,然后执行循环:
with open("sample_runner_data.csv", "r") as sample_csv:
sample_csv = csv.DictReader(sample_csv)
data = list(sample_csv)
for lines in data:
theLine = lines["team"]
for line in data:
if(theLine == line["team"]):
print(line["team"])
team.append(line["time"])
但是,如果您只是一直在寻找每个团队的聚会,这可能不是您想要的,例如:
data = {}
with open("sample_runner_data.csv", "r") as sample_csv:
sample_csv = csv.DictReader(sample_csv)
for line in sample_csv:
data.setdefault(line['team'], []).append(line['time'])
现在data
将包含team
作为键,所有time
作为值。