【问题标题】:How to add non-repeating elements in value of dictionary如何在字典的值中添加非重复元素
【发布时间】:2022-11-09 22:46:07
【问题描述】:

我想将列表中的每五个成员放入我的字典的值中,并且不应该在我的值中添加重复的数字,我需要以尽可能短的顺序在 python 中实现这个程序。

例如你的列表是 list= [9,9,9,2,3,4,5,5,6,6],你的字典应该是dict= {1: [9,2,3] , 2: [4,5,6] }

【问题讨论】:

标签: python list dictionary


【解决方案1】:

有很多可能的答案。这个不一定是最佳的:

为所有值创建一个集合:

unique_values = set()

创建空字典:

res = {1: []}

然后遍历列表:

for item in myList:
    if item not in unique_items:
        unique_items.add(item)
        if len(res[key]) == 3:
            key += 1
            res[key] = [item]
        else:
            res[key].append(item)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-14
    • 2019-08-20
    • 2022-03-08
    • 1970-01-01
    • 2019-09-23
    相关资源
    最近更新 更多