我想把我的列表中的每五个成员作为我的字典的值,但是重复的数字不应该添加在单个的值中,我需要以最短的顺序用Python实现这个程序。
例如,如果列表是lst = [9, 9, 9, 2, 3, 4, 5, 5, 6, 6]
,则结果字典应该是d = {1: [9, 2, 3], 2: [4, 5, 6]}
。
另一个例子是lst = [8, 6, 1, 9, 1, 0, 2, 8]
,结果字典是{1: [8, 6, 1, 9], 2: [0, 2, 8]}
。
发布于 2022-10-29 13:38:24
你可以用字典理解:
def fn(lst, n):
return {
idx: list(dict.fromkeys(lst[i : i + n]))
for idx, i in enumerate(range(0, len(lst), n), start=1)
}
print(fn([9, 9, 9, 2, 3, 4, 5, 5, 6, 6], 5))
print(fn([8, 6, 1, 9, 1, 0, 2, 8], 5))
产出:
{1: [9, 2, 3], 2: [4, 5, 6]}
{1: [8, 6, 1, 9], 2: [0, 2, 8]}
解释
您需要使用n
的步骤遍历列表。然后创建包含n
项的片。为了删除重复项,我使用了dict.fromkeys()
,它保留了插入顺序。同时,这些密钥也来自enumerate(..., start=1)
发布于 2022-10-29 13:35:10
一种将原始数组分块并在每个块中应用dict.fromkeys
并将其转换为dict的方法
a = [9,9,9,2,3,4,5,5,6,6]
def chunks(lst, n):
for i in range(0, len(lst), n):
yield lst[i:i + n]
l = [list(dict.fromkeys(chunk)) for chunk in chunks(a,5)]
d = {k+1:v for k,v in enumerate(l)}
print(d)
https://stackoverflow.com/questions/74245599
复制相似问题