我必须创建一个由字典组成的列表,例如:
submarines = [
'sub_1' : {'position':str(rand(11,55)), 'life':2},
'sub_2' : {'position':str(rand(11,55)), 'life':2},
'sub_3' : {'position':str(rand(11,55)), 'life':2},
'sub_4' : {'position':str(rand(11,55)), 'life':2}]
但首先我在上面的代码中犯了一个错误,因为我一遍又一遍地出错:
File "<ipython-input-132-f3fce9bb6d72>", line 2
'sub_1' : {'position':str(rand(11,55)), 'life':2},
^
SyntaxError: invalid syntax
我的目的是创建一个像战列舰这样的游戏,列表潜艇必须得到:
submarines['sub_...']['position][0]
除此之外,潜艇的数量必须尽可能多地修改,所以我尝试了这样的事情:
nb_subs = 4
for sub_id in range (nb_subs):
sub_x = [ str(sub_id): {int(submarines[sub_id]['position'][0])n 'life'=2}]
这样,列表潜艇中名为“sub _...”的词典数量将相应地设置为预先定义的nb_subs。但我仍然有错误......
我一直在为此苦苦挣扎。
答案 0 :(得分:1)
首先,考虑您是否需要以某种方式订购您的潜艇集合。如果是这样,那么创建一个像你在你的例子中所做的列表是有道理的:
avgPrice = (totalPrice)/(count);
context.write(new FloatWritable(avgPrice), NullWritable.get());
否则,如果订单无关紧要,那么根据juanpa's comment,使用大括号(from random import randint as rand
submarines = [
{'sub_1': {'position': str(rand(11, 55)), 'life': 2}},
{'sub_2': {'position': str(rand(11, 55)), 'life': 2}},
{'sub_3': {'position': str(rand(11, 55)), 'life': 2}},
{'sub_4': {'position': str(rand(11, 55)), 'life': 2}}
]
# give me the first item in this list. i want to see its
# sub_1 key, whose value is a dictionary, and then i want
# to get the value of that dictionary's life key.
print submarines[0]["sub_1"]["life"]
)制作字典,而不是包含单个潜艇:
{}