这些是我的投入
hand = {'*': 1, 'v': 2, 'n': 1, 'i': 1, 'l': 2}
string = 'abc'
我需要用字符串中的每个字符替换“ *”,并将新字典附加到列表中。我需要的输出是这样的:
[{'v': 2, 'n': 1, 'i': 1, 'l': 2, 'a': 1}, {'v': 2, 'n': 1, 'i': 1, 'l': 2, 'b': 1}, {'v': 2, 'n': 1, 'i': 1, 'l': 2, 'c': 1}]
这是我所做的,但是没有用。我尝试了几种不同的方法,但没有成功。
del hand['*']
for x in string:
item = {x: 1}
newHand = hand
newHand.update(item)
print(newHand)
list.append(newHand)
newHand.pop(x)
print(list)
下面的输出是我要避免的事情:
{'v': 2, 'n': 1, 'i': 1, 'l': 2, 'a': 1, 'b': 1, 'c': 1}
谢谢
这将为相同的数据创建一个新名称:
newHand = hand
您始终在修改同一词典。您将引用存储到您的引用中list
(顺便说一句,不要将其list
用作变量名,而是对内置的阴影list()
)。如果您打印id()
清单内容中的,您将看到它们都是相同的:
print( id(x) for x in list) # try that to see its the same object trice
您需要复制数据来创建三个不同的字典。
我选择dict
从您的位置更新1-elem ,string
并用hand
pop之后的其余部分更新它们'*'
:
hand = {'*': 1, 'v': 2, 'n': 1, 'i': 1, 'l': 2}
s = hand.pop("*") # removes * and stores the calue
t = "abc"
# create a list of new dicts wich 1 elem each
l = [ {c:s} for c in t]
# update all inner dicts
for d in l:
d.update(hand) # add what is in hand left
print(l)
输出:
[{'a': 1, 'i': 1, 'v': 2, 'l': 2, 'n': 1},
{'i': 1, 'b': 1, 'v': 2, 'l': 2, 'n': 1},
{'i': 1, 'c': 1, 'v': 2, 'l': 2, 'n': 1}]
您可以在此处找到有关可变变量复制的更多信息:如何克隆或复制列表?
也要更新现有密钥:
for d in l:
for thing in hand:
d.setdefault(thing,0) # create key if not exists and set to 0
d[thing] += hand[thing] # add hands value on top
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句