def main():
winners = []
winnersND = []
readData()
noDuplicates(winners)
def readData():
winners_file = open('WorldSeriesWinners.txt', 'r')
winners = winners_file.readlines()
winners_file.close()
index = 0
while index < len(winners):
winners[index] = winners[index].rstrip('\n')
index += 1
print(winners)
print()
print()
return winners
def noDuplicates(winners):
winnersND = []
for x in winners:
if x not in winnersND:
winnersND.append(x)
print (winnersND)
winnersND = tuple(winnersND)
return winnersND
main()
所以我一直在寻找各处,我已经经历了七个小时的代码迭代试图让这项工作,但由于某种原因,获奖者名单打印在readData()
,但是winnersND
列表(唯一和有序的获胜者列表元素列表)不会被打印,而是显示输出:[]
。我很想澄清一下我在这里搞砸了什么。谢谢!
答案 0 :(得分:0)
因为winners
是main
是一个空列表。您在winners
中重新分配了名为readData()
的变量并将其返回,但您没有捕获返回值。因此main
继续将空winners
列表传递给noDuplicates()
。
尝试将main
更改为:
def main():
winners = readData()
winnersND = noDuplicates(winners)
答案 1 :(得分:0)
您的问题在这里:
winners = readData() # you need to return the list here...
noDuplicates(winners) # otherwise it's empty here.
这一切都可以这样做。
def main():
winners = [x.rstrip() for x in open('WorldSeriesWinners.txt').readlines()]
winnersND = list(set(winners))
由于您在评论中提到了这一点,因此您可以查看每个团队获胜的次数。
from collections import Counter
for winner, count in Counter(winners).iteritems():
print '{0} has won {1} times'.format(winner, count)
答案 2 :(得分:-1)
尝试
print winners
在noDuplicates()
函数中,
这是一个空白列表,这就是为什么你得到一个空白列表,因为从空白列表中获取数据。
您尝试访问winners
中指定的main()
,但在readData()
功能中更改winners
,当您尝试访问该功能外的def noDuplicates(winners):
winnersND = []
for x in readData(): # use readData() instead winners
if x not in winnersND:
winnersND.append(x)
print (winnersND)
winnersND = tuple(winnersND)
return winnersND
时,它会显示空白列表。
试试这个: -
readData()
或将data = readData()
存储在变量中,以便: -
for
然后应用for x in data:
.
.
循环
{{1}}