【问题标题】:Dictionary of lists and list of tuples comparison列表字典和元组列表比较
【发布时间】:2021-04-13 17:11:48
【问题描述】:

所以我试图让我的列表字典与我的元组列表相匹配。 (希望这是有道理的)。我有一本以列表为值的字典,我的值是每本书的单独分数,例如:bob 上的值 5 将等于书单中的第一本书,:

d = {'bob':[5,0,0,1,3], 'toms':[3,0,5,3,0], 'sammy': [0,0,0,1,0], 'ted':[5,0,0,6,3]}

还有一个元组列表:

books=[('Douglas Adams', "The Hitchhiker"), ('Richard Adams', 'Watership'), ('Mitch Albom', 'The Five People'), ('Laurie Anderson', 'Speak'), ('Maya Angelou', 'Caged Bird Sings')]

所以我想要的是能够以某种方式说出当某人的价值为 3 或 6 时,我可以将他们拉出来说出哪些书有这些评级。 谢谢!

编辑: 我希望它输出某种字典,它会说:

selectScores = {bob: ('Maya Angelou', 'Caged Bird Sings'), toms: (Maya Angelou', 'Caged Bird Sings', Laurie Anderson', 'Speak')} 

每个人都以此类推

类似的东西我希望成为输出。

【问题讨论】:

  • 你有什么问题?请edit 澄清。如果您正在寻找编写代码的帮助,您已经尝试过什么? SO 不是代码编写服务,但我们很乐意帮助您编写代码。如果您想了解更多提示,请参阅How to Ask
  • 您的问题并不完全清楚,也许您可​​以edit 包含您的预期输出,并根据您自己的研究为您迄今为止尝试过的内容提供代码制作一个minimal reproducible example
  • 你能添加一些预期的输出吗?我不太明白您所说的“当某人的值为 3 或 6”时是什么意思

标签: python list dictionary tuples


【解决方案1】:

你可以试试这样的。基本上枚举字典值并使用它的索引来访问书籍数组。

d = {'bob':[5,0,0,1,3], 'toms':[3,0,5,3,0], 'sammy': [0,0,0,1,0], 'ted':[5,0,0,6,3]}
books=[('Douglas Adams', "The Hitchhiker"), ('Richard Adams', 'Watership'), ('Mitch Albom', 'The Five People'), ('Laurie Anderson', 'Speak'), ('Maya Angelou', 'Caged Bird Sings')]

select_scores = {}
for key, books_scores in d.items():
    for i, score in enumerate(books_scores):
        if score == 3 or score == 6:
            if key not in select_scores:
                select_scores[key] = []
            select_scores[key].append(books[i])
            
print(select_scores)

输出:

{'bob': [('Maya Angelou', 'Caged Bird Sings')], 'toms': [('Douglas Adams', 'The Hitchhiker'), ('Laurie Anderson', 'Speak')], 'ted': [('Laurie Anderson', 'Speak'), ('Maya Angelou', 'Caged Bird Sings')]}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-24
    • 2012-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多