我想定义字典如下:
dict = {
Player: $key.Name + " takes some action"
}
有没有一种语法可以让我这样做?
字典理解可能会有所帮助。
>> players = ["Mark", "Jack", "John"]
>> player_dict = {k: k + " takes some action" for k in players}
>> player_dict
{'John': 'John takes some action', 'Jack': 'Jack takes some action', 'Mark': 'Mark takes some action'}
它们采用{
键值:
变量for
生成in
器的形式}
class Player(object):
def __init__(self, name):
self.name = name
p1 = Player("bernard")
p2 = Player("hoagie")
t = (p1, p2, ...)
d = {p: p.name + " something something" for p in t}
听起来您想在分配给该键的值中使用您正在创建的键。是的,这是可能的:
playerDict = {Player: Player + " takes some action"}