简体   繁体   English

如何为列表中的每个人分配一个数字?

[英]How to assign a number to each person in list?

I'm struggling to think of a function that allows me to assign a number to each person in terms of their hierarchy eg person 1 with rank of 1 has a higher no.我正在努力想出一个函数,它允许我根据他们的层次结构为每个人分配一个数字,例如,等级为 1 的人 1 具有更高的编号。 than other players比其他玩家

 People = ["Tz", "Bs", "Ds", "Kk", "Os", "Vs", "Dn"]

You can use dictionary instead of list .您可以使用dictionary而不是list I would suggest you use from collections import defaultdict .我建议您使用from collections import defaultdict By this way, you can even assign a tuple to one key.通过这种方式,您甚至可以为一个键分配一个元组。 Even more, if you just passed the same key multiple times with different values it will store them under the same key.更重要的是,如果您只是多次使用不同的值传递相同的键,它会将它们存储在同一个键下。

>>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
>>> d = defaultdict(list)
>>> for k, v in s:
...     d[k].append(v)
...
>>> sorted(d.items())
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]

You need a dictionary for this.为此,您需要一本字典。 Players = { "Rz": 1, "As" : 2 } It would be in the format {"player_name": strength} Players = { "Rz": 1, "As" : 2 } 格式为 {"player_name": strength}

You can solve it via using a dictionary, but there's also a design pattern where you'd use a second list.您可以通过使用字典来解决它,但也有一种设计模式,您可以使用第二个列表。

players = ["Rz", "As", "Ts", "Dk", "Ms", "Ss", "Pn"]
strength = [5, 4, 3, 2, 1, 0, 0]

This would mean you can access the first players strength by its index in the players list.这意味着您可以通过其在球员列表中的索引来访问第一名球员的实力。

players[0]
strenght[0]

This, of course, needs you to keep the players in the same order.当然,这需要您让玩家保持相同的顺序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM