【问题标题】:create a key- value pair in a for loop using python and update the value使用python在for循环中创建一个键值对并更新值
【发布时间】:2018-07-02 20:35:51
【问题描述】:

我是 python 新手,从头开始学习。我想做的一件事,但不知道如何使用 for 循环创建键值对列表并仅更新值。示例代码是:

for i in range(0,6)
  #####some code that gives an output integer x.
  print(i,x)

整数 x 对于每个 i 都是不同的。如何使用 for 循环创建类似 {0:x0,1:x1,2:x2,3:x3,4:x4,5:x5} 的列表?

【问题讨论】:

  • 那不是列表,那是dict。你想要list 还是dict
  • 您的示例中的值x0 是字符串文字'x0',还是x 代表什么?它来自哪里?
  • @pushkin 大概来自“一些给出输出整数 x 的代码”
  • 对不起,我想要一本字典。而x1,x2等只是x在每次迭代中的不同整数值。
  • 为什么要字典?您的数据看起来应该是一个列表。

标签: python python-3.x list dictionary for-loop


【解决方案1】:

您正在寻找Python Dictionaries

sample = {}
for i in range(6):
   # some code that gives you x
   sample[i] = x
print(sample)

但是请注意,由于您的密钥只是 0, 1, 2 等,您可能只想使用一个列表来代替:

sample = []
for i in range(6):
    # some code that gives you x
    sample.append(x)
print(sample)

请注意,使用sample[key] 的字典访问看起来与使用sample[index] 的列表访问相同,因为您只是使用连续的数字键。

【讨论】:

    【解决方案2】:

    这是你要找的吗?

    dic = {}
    x = "8"
    for i in range(6):
        #calculate x
        dic[i] = int(str(x)+str(i))
    
    print(dic)
    
    {0: 80, 1: 81, 2: 82, 3: 83, 4: 84, 5: 85}
    

    【讨论】:

      猜你喜欢
      • 2021-03-24
      • 2020-05-16
      • 2021-11-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-03
      • 1970-01-01
      • 1970-01-01
      • 2017-02-13
      相关资源
      最近更新 更多