我想将每个价格值存储在数组中,从dict中获取它。我是蟒蛇新手,我花了好几个小时试图解决这个问题......
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]
答案 0 :(得分:6)
定义list并附加到其中:
prices = []
for item in world_dict:
if item[1] == 'House':
price = float(item[2])
prices.append(price)
print(price)
或者,您可以使用list comprehension:
以更短的方式编写它prices = [float(item[2]) for item in world_dict if item[1] == 'House']
print(prices)
希望有所帮助。
答案 1 :(得分:0)
这是一个简单的示例,说明如何使用python中的for循环将值存储到数组中
希望这将有助于新生在搜索上述问题时有所收获
list = [] #define the array
#Fucntion gets called here
def gameConfiguration():
n= int(input("Enter Number of Players : "))
for i in range(0, n):
ele = (input("Name : "))
list.append(ele) # adding the element to the array
print(list[0]) #so you can print the element 1
print(list[1]) #so you can print the element 2 so on and soforth
gameConfiguration() # starts the execution of the fuction