Python - 将一个值存储在一个 for 循环内的数组中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22740512/
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
Python - Store a value in an array inside one for loop
提问by A. Ayres
I would like to store each value of price in an array, getting it from a dict. I am a fresh at python, I spent hours trying to figure this out...
我想将价格的每个值存储在一个数组中,从字典中获取它。我是 python 的新手,我花了几个小时试图解决这个问题......
for item in world_dict:
if item[1] == 'House':
price = float(item[2])
print p
The output is like:
200.5
100.7
300.9
...
n+100
However, I want to store it on this format : [200.5, 100.7, 300.9, ..., n+100]
但是,我想以这种格式存储它:[200.5, 100.7, 300.9, ..., n+100]
采纳答案by alecxe
Define a listand append to it:
定义一个列表并附加到它:
prices = []
for item in world_dict:
if item[1] == 'House':
price = float(item[2])
prices.append(price)
print(price)
or, you can write it in a shorter way by using list comprehension:
或者,您可以使用列表理解以更短的方式编写它:
prices = [float(item[2]) for item in world_dict if item[1] == 'House']
print(prices)
Hope that helps.
希望有帮助。