我想按如下方式定义字典:
dict = {
Player: $key.Name + " takes some action"
}
是否有允许我这样做的语法?
答案 0 :(得分:2)
字典理解可能会有所帮助。
>> 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
变量 {{1} } 发生器 in
答案 1 :(得分:1)
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}
答案 2 :(得分:0)
听起来您想要在分配给该密钥的值中使用您创建的密钥。是的,这是可能的:
playerDict = {Player: Player + " takes some action"}