【问题标题】:Python - Store a value in an array inside one for loopPython - 在一个for循环内的数组中存储一个值
【发布时间】:2014-05-09 13:10:19
【问题描述】:

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

【问题讨论】:

  • 您只想要这些值吗?喜欢word_dict.values()?
  • @ssm 这是迭代有点奇怪的地方。如果world_dict 是一个字典,那么 OP 会根据输出对作为元组的键进行迭代。
  • @alecxe 我不知道您可以在字典中使用相同的键存储多个值。所以如果House是key,那他不就是想做word_dict['Hoise']吗?我有点困惑...... :(

标签: python string for-loop


【解决方案1】:

最简单的方法是将for循环的值存储在数组中。

from array import *

ar = []

for i in range (0, 5, 1) :

    x = 3.0*i+1
    
    ar.append(x)
    
print(ar)

这样的输出;

[1.0, 4.0, 7.0, 10.0, 13.0]

【讨论】:

    【解决方案2】:

    这是一个如何在 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
    

    【讨论】:

      【解决方案3】:

      定义一个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)
      

      希望对您有所帮助。

      【讨论】:

      • 非常感谢您的帮助。谢谢你。这正是我正在寻找的
      猜你喜欢
      • 2022-01-11
      • 1970-01-01
      • 1970-01-01
      • 2014-05-17
      • 2022-01-25
      • 1970-01-01
      • 1970-01-01
      • 2011-01-30
      • 1970-01-01
      相关资源
      最近更新 更多