为什么这个python 3 for循环不起作用?

时间:2018-06-05 17:42:21

标签: python python-3.x for-loop

我正在尝试获得一个输出:

We won in *year x*!!

All about the U!!

我想在列表中每年重复一遍,因此输出结果为:

We won in 1983!!

All about the U!!

We won in 1987!!

All about the U!!

ect. repeat for each year.

我一直坚持的是:

We won in [1983, 1987, 1989, 1991, 2001]!!

All about the U!!

*repeated for the length of the list, 5 times*

以下是我尝试过的代码:

yearlist = [1983, 1987, 1989, 1991, 2001]

for wewon in yearlist:
    print("We won in {}!!".format(yearlist))
    print("All about the U!!")

我哪里出错?

3 个答案:

答案 0 :(得分:4)

您想要使用循环变量(wewon),而不是列表(yearlist):

print("We won in {}!!".format(wewon))

wewon将采用yearlist的每个值。

答案 1 :(得分:0)

@John ,请尝试以下代码:

  

在每次迭代中,您将获得分配给 wewon 的列表项目,这是一年,所以不要在print()函数中使用list

     

您可以在http://rextester.com/GDIT18485

尝试以下代码
yearlist = [1983, 1987, 1989, 1991, 2001]

for wewon in yearlist:
    print("We won in {}!!".format(wewon))
    print("All about the U!!")

✓输出:

We won in 1983!!
All about the U!!
We won in 1987!!
All about the U!!
We won in 1989!!
All about the U!!
We won in 1991!!
All about the U!!
We won in 2001!!
All about the U!!

答案 2 :(得分:0)

这两个好的解决方案,但我对迭代事件只有不自然的喜爱......

In [65]: yr = (i for i in ('1983', '1987', '1989', '1991', '2001'))    

In [66]: type(yr)    
Out[66]: generator    

In [67]: while True:    
    ...:     try:    
    ...:         print(f'We won in {next(yr)}!!\nAll about the U!!')    
    ...:     except StopIteration:    
    ...:         pass    
    ...:         break    

输出:
我们在1983年获胜!!
所有关于U !!
我们在1987年获胜!!
所有关于U !!
我们在1989年赢了!!
所有关于U !!
我们在1991年获胜!!
所有关于U !!
我们在2001年获胜!!
所有关于你的!!