[英]How do you loop through a list to a variable and print the value outside of the loop?
I am trying to loop through a list and make a variable that contains the list + some other info to be able to use it outside the for loop, however when I print my variable outside the loop I only get the last item in the list.我试图遍历一个列表并创建一个包含列表 + 一些其他信息的变量,以便能够在 for 循环之外使用它,但是当我在循环之外打印我的变量时,我只能得到列表中的最后一项。 I want to see all of them in the list.我想在列表中看到所有这些。
#!/usr/bin/python
a = ['apple', 'orange', 'peanut']
for item in a:
mylist = '*' + item
print item
print "------out of loop ----------"
print mylist
The output is:输出是:
apple
orange
peanut
------out of loop ----------
*peanut
you have to declare mylist outside of the loop.你必须在循环之外声明 mylist 。 also you need to use '+=' (append) to keep adding onto mylist您还需要使用 '+=' (append) 继续添加到 mylist
a = ['apple', 'orange', 'peanut']
mylist = ''
for item in a:
mylist += '*' + item
print(item)
print("------out of loop ----------")
print(mylist)
this output should be :这个输出应该是:
apple
orange
peanut
------out of loop ----------
*apple*orange*peanut
With mylist = '*' + item
you always overwrite the old value of mylist
使用mylist = '*' + item
你总是覆盖mylist
的旧值
If you want to keep it, you should do something like mylist = mylist + '*' + item
, depending on what you want to display如果你想保留它,你应该做类似mylist = mylist + '*' + item
事情,这取决于你想要显示的内容
Or a different solution would be mylist += '*' + item
或者不同的解决方案是mylist += '*' + item
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.