Python 如何将for循环输出转换为列表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33390493/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert a for loop output to a list?
提问by Sbioer
For example:
例如:
for y,x in zip(range(0,4,1),range(0,8,2)):
print(x+y)
Returns:
返回:
0
3
6
9
What I want is:
我想要的是:
['0', '3', '6', '9']
How can I achieve this?
我怎样才能做到这一点?
采纳答案by Avión
The easiest way for your understanding, without using list comprehension, is:
不使用列表理解的最简单方法是:
mylist = []
for y,x in zip(range(0,4,1),range(0,8,2)):
mylist.append(str(x+y))
print mylist
Output:
输出:
['0','3','6','9']
回答by itzMEonTV
Try this using list comprehension
使用列表理解试试这个
>>>[x+y for y,x in zip(range(0,4,1),range(0,8,2))]
[0, 3, 6, 9]
>>>[str(x+y) for y,x in zip(range(0,4,1),range(0,8,2))]
['0', '3', '6', '9']
回答by Eugene Soldatov
You can generate list dynamically:
您可以动态生成列表:
print [str(x+y) for x, y in zip(range(0,4,1), range(0,8,2))]
['0','3','6','9']
This technique called list comprehensions.
这种技术称为列表推导。
回答by SirParselot
You could skip the for loops and use map()and import addfrom operator
您可以跳过 for 循环并使用map()和导入addfromoperator
from operator import add
l = map(add,range(0,4,1),range(0,8,2))
print l
[0, 3, 6, 9]
And if you want it as strings you could do
如果你想要它作为字符串你可以做
from operator import add
l = map(add,range(0,4,1),range(0,8,2))
print map(str, l)
['0','3', '6', '9']

