我有两个字串“糖果-一”和“糖果-二”作为关键和容量作为关键对。我希望将字符串"Candy-one“和”Candy-2“替换为"Candy-one”和“Candy-2”这两个位置上有相同糖果的品牌名称。
这就是我试过的
p = [['Brand-Name', 'Swap', ' Candy-one ', ' Candy-two ', 'Capacity'],
['Willywonker', 'Yes', 'bubblegum', 'mints', '7'],
['Mars-CO', 'Yes', 'chocolate', 'bubblegum', '1'],
['Nestle', 'Yes', 'bears', 'bubblegum', '2'],
['Uncle Jims', 'Yes', 'chocolate', 'bears', '5']]
f = {('bubblegum', 'mints'): 4,
('chocolate', 'bubblegum'): 1,
('bears', 'bubblegum'): 2,
('chocolate', 'bears'): 2}
def Brand(f,p):
i = 0
while i < len(p)-1:
i = i + 1
for key in f:
print(key[0])
print(key[1])
if key[0] == p[i][2] and key[1] == p[i][3]:
f[p[i][0]] = key.pop(key)
return f
print(brand(f,p))这是我的输出
{('bubblegum', 'mints'): 4,
('chocolate', 'bubblegum'): 1,
('bears', 'bubblegum'): 2,
('chocolate', 'bears'): 2}好像什么都没发生,这就是我想要的输出
{'Willywonker': 4,
'Mars-CO': 1,
'Nestle': 2,
'Uncle Jims': 2}发布于 2022-05-06 13:34:42
使用双环不是有效的(二次复杂度)。
下面是我解决这个问题的方法:
def Brand(f,p):
# create a mapping dictionary
d = {tuple(x[2:4]): x[0] for x in p[1:]}
# output a new dictionary with replaced keys
# or old key if a new one is not found
return {d.get(k, k): v for k,v in f.items()}
# or if you want to drop in case of no match
# return {d[k]: v for k,v in f.items() if k in d}
Brand(f,p)产出:
{'Willywonker': 4,
'Mars-CO': 1,
'Nestle': 2,
'Uncle Jims': 2}发布于 2022-05-06 13:29:08
def Brand(f,p):
res={}
i = 0
while i < len(p)-1:
for key in f:
if key[0] == p[i+1][2] and key[1] == p[i+1][3]:
res[p[i+1][0]] = f[key]
i += 1
return res
new_dict = Brand(f,p)
print(new_dict)
{'Willywonker': 4, 'Mars-CO': 1, 'Nestle': 2, 'Uncle Jims': 2}或者你纠正的企图:
def Brand(f,p):
res=f.copy()
i = 0
while i < len(p)-1:
for key in f:
if key[0] == p[i+1][2] and key[1] == p[i+1][3]:
res[p[i+1][0]] = res.pop(key)
i += 1
return res
updated_dict = Brand(f,p)
print(updated_dict)
{'Willywonker': 4, 'Mars-CO': 1, 'Nestle': 2, 'Uncle Jims': 2}发布于 2022-05-06 13:21:07
作为一个元组,key没有pop方法,这意味着您从未真正尝试更改f (可能是因为您从未调用Brand)。
加上@quamrana显示的东西。
https://stackoverflow.com/questions/72142063
复制相似问题