python - 将值存储在一个 for 循环内的数组中

标签 python string for-loop

我想将价格的每个值存储在一个数组中,从字典中获取它。我是 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

但是,我想以这种格式存储它:[200.5, 100.7, 300.9, ..., n+100]

最佳答案

定义一个 list并附加到它:

prices = []
for item in world_dict:
     if item[1] == 'House':
       price = float(item[2])
       prices.append(price)

print(prices)

或者,您可以使用 list comprehension 以更短的方式编写它:

prices = [float(item[2]) for item in world_dict if item[1] == 'House']
print(prices)

关于python - 将值存储在一个 for 循环内的数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22740512/

相关文章:

python - 如何使用日期时间在python中获取给定日期的下个月的同一天

string - 双方括号和单方括号 [ 和 [[ 以及等号 = 和 == 有什么区别?

r - 输入到函数的行名的 For 循环

python - uuid.uuid4() 在具有多处理功能的 Windows 上使用是否安全?

python - 使用 format() 迷你语言将 float 与 Python 2.7 中的小数点对齐

string - Powershell,函数在连接字符串(参数)时添加尾随空格

Javascript字符串通过连接构造?

php - 逗号在for循环的第一个参数中起什么作用?

停止和等待算法的 Python 实现

python - 如何将值从 Python Pandas 中的多个字典对象插入到数据帧中