如何将字典值的总和分配给变量?

时间:2014-02-08 19:11:52

标签: python dictionary raw-input

此词典由用户创建:

p2u = raw_input("Player 2 enter the amount of units you have: ")
if p2u == 1:
    p2d={'Unit 1': 50}
    p2units = 50
if p2u == 2:
    p2d={'Unit 1': 50, 'Unit 2': 50}
    p2units = 100
if p2u == 3:
    p2d={'Unit 1': 50, 'Unit 2': 50, 'Unit 3': 50}
    p2units = 150 

现在让我们说用户输入3,如何使变量之和等于一个名为'Amount'的变量?

5 个答案:

答案 0 :(得分:2)

这有效:

amount = 0

for key, value in p2d.items():
    amount += value

或者

amount = sum(p2d.values())

您需要以下内容:

p2u = int(raw_input("Player 2 enter the amount of units you have: "))

当你的raw_input给出一个字符串('1'等)时你的if语句正在检查整数

答案 1 :(得分:0)

您可以尝试sum() built-in function

p2d = {'Unit 1': 50, 'Unit 2': 50, 'Unit 3': 50}
amount = sum(p2d.values())

另请注意,p2u是一个字符串(如果要测试变量类型print type(p2u)),请在if语句中将其与int进行比较。你可以通过两种方式解决这个问题。

首先,将p2u转换为整数:

p2u = int(raw_input(...))

第二种方法,将p2u(作为字符串)与字符串进行比较:

p2u = raw_input(...)
if p2u == "1":
    ...

答案 2 :(得分:0)

我不太清楚这个问题后面有什么价值。以下代码将汇总来自任何p2d词典的所有值:

Amount = sum(p2d.values())

列出值完成:

>>> p2d={'Unit 1': 50, 'Unit 2': 50, 'Unit 3': 50}
>>> p2d.values()
[50,50,50]

在列表中添加数字:

sum([50,50,50])

答案 3 :(得分:0)

  1. raw_input的输出是一个字符串,而不是整数。将其翻译为整数:

    p2u = int(p2u)

  2. 使用sum:

    p2units = sum(p2d.values())

答案 4 :(得分:0)

这是一个扩展版本:

import sys

# Python 2/3 compatibility shim
if sys.hexversion < 0x3000000:
    inp = raw_input
    rng = xrange
else:
    inp = input
    rng = range

def get_int(prompt):
    while True:
        try:
            return int(inp(prompt))
        except ValueError:
            pass

class Unit:
    def __init__(self, name, men=50):
        self.name = name
        self.men  = men

    def __str__(self):
        return "{:5s}: {} men".format(self.name, self.men)

class Player:
    def __init__(self, name, units=None):
        self.name = name
        if units is None:
            units = get_int("How many units does {} have? ".format(self.name))
        self.units = [Unit("Unit {}".format(i)) for i in rng(1, units+1)]

    @property
    def men(self):
        return sum(u.men for u in self.units)

    def __str__(self):
        units = ''.join("\n  {}".format(u) for u in self.units)
        return "{}{}\nTotal: {} men".format(self.name, units, self.men)

def main():
    num_players = get_int("How many players? ")
    players = [Player("Player {}".format(i)) for i in rng(1, num_players+1)]

    print('')
    print("\n\n".join(str(p) for p in players))

if __name__ == "__main__":
    main()

一样运行
How many players? 3
How many units does Player 1 have? 2
How many units does Player 2 have? 1
How many units does Player 3 have? 9

Player 1
  Unit 1: 50 men
  Unit 2: 50 men
Total: 100 men

Player 2
  Unit 1: 50 men
Total: 50 men

Player 3
  Unit 1: 50 men
  Unit 2: 50 men
  Unit 3: 50 men
  Unit 4: 50 men
  Unit 5: 50 men
  Unit 6: 50 men
  Unit 7: 50 men
  Unit 8: 50 men
  Unit 9: 50 men
Total: 450 men