字典列表上的数学运算(python 3.6)

时间:2018-05-23 03:03:12

标签: python-3.x

我正在使用python 3.6,我有一个像这样的字典列表:

list = [{'name': 'A', 'number':'1'}, {'name': 'B', 'number':'2'}, {'name': 'C', 'number':'3'}, {'name': 'D', 'number':'4'}]

我找到了如何使用以下格式打印所需格式的列表:

for s in list:
     name = s['name']
     number = s['number']
     print(name + " = "+ number)

给予:

  

A = 1
  B = 2
  C = 3
  D = 4

我希望能够将项目'number'乘以2,例如显示:

  

A = 2
  B = 4
  C = 6
  D = 8

谢谢!

2 个答案:

答案 0 :(得分:1)

您是否尝试暂时将这些值相乘并将其打印出来?在这种情况下,您可以将最后一行更改为

print(name + " = "+ int(number) * 2)

但是,如果你想直接将字典中的值相乘,你可以这样做:

for s in list:
 name = s['name']
 s['number'] = str(int(s['number']) * 2)         # multiply value by 2
 number = s['number']
 print(name + " = "+ number)

请注意,您的问题可能源于您的字典值存储为字符串而不是整数,这意味着要对它们执行任何类型的数学运算,您必须将它们转换为整数并返回字符串。

答案 1 :(得分:0)

您可以随时遍历列表以修改其嵌套部分的值,即:

your_list = [{'name': 'A', 'number': '1'},
             {'name': 'B', 'number': '2'},
             {'name': 'C', 'number': '3'},
             {'name': 'D', 'number': '4'}]

for item in your_list:  # iterate over each dictionary in your_list
    # since your dict contains strings we have to convert the value into a number/integer
    # before multiplying it by 2
    item["number"] = int(item["number"]) * 2  # turn it back to a string with str() if needed

# now, let's demonstrate that the data changed in `your_list`:
for item in your_list:  # iterate over each dictionary in your_list
    print("{} = {}".format(item["name"], item["number"]))  # print in your desired format
# A = 2
# B = 4
# C = 6
# D = 8