【问题标题】:Change values in a list to those specified in a dictionary?将列表中的值更改为字典中指定的值?
【发布时间】:2022-01-13 01:27:52
【问题描述】:

我有一个包含成对元组的列表,第一个元素是名称(字符串),第二个元素是包含该人去过的餐馆的列表。 我有一个包含此类餐厅分数的字典。因此,如果人 A 去过餐馆(x,y,z) 因此,[('A', ['x', 'y', 'z'])] 并且我的字典指出{'x':10, 'y':23, 'z':33}。如何将餐厅名称替换为包含名称的字典中指定的数字? 输出[('A', [10, 23, 33])]。 在那之后,我想把这些数字加起来有[('A', [66])]

谢谢。 这是我正在使用的代码:

restaurants_attended = [('Aariz Lambert', ['The Beach Chimney', 'Parlay', 'The Private Exhibit']), ('Ariya Collier', ['Seawise', 'Enigma', 'Midnight'])]
{'The Beach Chimney': 201.0, "The Pirate's Harvest": 154.0, 'The Square Dragon': 132.0, 'The Spicy Trumpet': 266.0, 'Vertigo': 204.0, 'Drifters': 183.0, 'The Tulip': 156.0, 'Seawise': 136.0, 'Parlay': 140.0, 'The Modern Salmon': 176.0, 'The Bitter Windmill': 139.0, 'The Minty Window': 166.0, 'The Private Exhibit': 189.0, 'Enigma': 228.0, 'The Lighthouse': 159.0, 'Harlequin': 131.0, 'Midnight': 141.0, 'Gastrognome': 166.0}

【问题讨论】:

  • 这不是代码编写服务。你真的尝试过这样做吗?您使用的代码只是数据。你需要问一个更具体的问题。
  • 我已经尝试了一段时间,但我无法让它工作。如果我浏览整个代码会很长,这只是最后一步。

标签: python python-3.x list dictionary


【解决方案1】:

你可以使用dict理解:

restaurants_attended = [('Aariz Lambert', ['The Beach Chimney', 'Parlay', 'The Private Exhibit']), ('Ariya Collier', ['Seawise', 'Enigma', 'Midnight'])]
scores = {'The Beach Chimney': 201.0, "The Pirate's Harvest": 154.0, 'The Square Dragon': 132.0, 'The Spicy Trumpet': 266.0, 'Vertigo': 204.0, 'Drifters': 183.0, 'The Tulip': 156.0, 'Seawise': 136.0, 'Parlay': 140.0, 'The Modern Salmon': 176.0, 'The Bitter Windmill': 139.0, 'The Minty Window': 166.0, 'The Private Exhibit': 189.0, 'Enigma': 228.0, 'The Lighthouse': 159.0, 'Harlequin': 131.0, 'Midnight': 141.0, 'Gastrognome': 166.0}

output = {person: [scores[r] for r in rests] for person, rests in restaurants_attended}
print(output) # {'Aariz Lambert': [201.0, 140.0, 189.0], 'Ariya Collier': [136.0, 228.0, 141.0]}
output_sum = {person: sum(scores) for person, scores in output.items()}
print(output_sum) # {'Aariz Lambert': 530.0, 'Ariya Collier': 505.0}

如果您想要指定的元组列表,请使用list,如下所示:

print(list(output.items())) # [('Aariz Lambert', [201.0, 140.0, 189.0]), ('Ariya Collier', [136.0, 228.0, 141.0])]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-07
    相关资源
    最近更新 更多