Python 字典中的值可以有两个值吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4840249/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can a value in a Python Dictionary have two values?
提问by Zack Shapiro
For a test program I'm making a simple model of the NFL. I'd like to assign a record (wins and losses) to a team as a value in a dictionary? Is that possible?
对于测试程序,我正在制作 NFL 的简单模型。我想将记录(输赢)作为字典中的值分配给团队?那可能吗?
For example:
例如:
afcNorth = ["Baltimore Ravens", "Pittsburgh Steelers", "Cleveland Browns", "Cincinatti Bengals"]
If the Ravens had 13 wins and 3 loses, can the dictionary account for both of those values? If so, how?
如果乌鸦队 13 胜 3 负,字典可以解释这两个值吗?如果是这样,如何?
采纳答案by Spacedman
sure, just make the value a list or tuple:
当然,只需将值设为列表或元组:
afc = {'Baltimore Ravens': (10,3), 'Pb Steelers': (3,4)}
If it gets more complicated, you might want to make a more complicated structure than a tuple - for example if you like dictionaries, you can put a dictionary in your dictionary so you can dictionary while you dictionary.
如果它变得更复杂,你可能想要制作一个比元组更复杂的结构——例如,如果你喜欢字典,你可以在你的字典中放一个字典,这样你就可以一边字典一边查字典。
afc = {'Baltimore Ravens': {'wins':10,'losses': 3}, 'Pb Steelers': {'wins': 3,'losses': 4}}
But eventually you might want to move up to classes...
但最终你可能想要升级到课堂......
回答by Sven Marnach
The values in the dictionary can be tuples or, maybe better in this case, lists:
字典中的值可以是元组,或者在这种情况下可能更好的是列表:
d = {"Baltimore Ravens": [13, 3]}
d["Baltimore Ravens"][0] += 1
print d
# {"Baltimore Ravens": [14, 3]}
回答by Andrew Jaffe
Well, you can use a tuple (or a list):
好吧,您可以使用元组(或列表):
records = {}
records["Baltimore Ravens"] = (13, 3)
Or you could be fancy and make a Recordclass with Record.winsand record.losses, but that's probably overkill.
或者你可以看中,并作出Record类Record.wins和record.losses,但是这可能矫枉过正。
(As another answer points out, using a list means that you can do arithmetic on the values, which might be useful.)
(正如另一个答案指出的那样,使用列表意味着您可以对值进行算术运算,这可能很有用。)

