gpt4 book ai didi

python - 从字典中不等长度的元素形成元组列表

转载 作者:太空宇宙 更新时间:2023-11-03 19:58:23 25 4
gpt4 key购买 nike

我有一本字典,其值的长度不等。

示例:

d= {'190': ['229'], '192': ['205'], '193': ['259'], '194': ['196', '204', '242', '249', '254', '266', '299', '302', '346'], '195': ['218', '273', '275', '306', '328'], '196': ['204', '249', '254', '266', '285', '330', '346'], '197': ['251', '272', '281', '284', '309', '320', '329'], '198': ['348', '351', '364', '393', '399', '441', '476', '501', '549', '564'], '199': ['200', '203', '211', '212', '222', '223', '231', '232', '238', '239', '252', '261', '265', '271', '288', '291', '298', '304', '313', '314', '315', '322', '324', '325', '342'], '200': ['203', '223', '224', '232', '236', '239', '248', '252', '271', '274', '276', '277', '280', '285', '297', '304', '322', '323', '324', '325', '332', '334'], '201': ['259'], '202': ['329'], '203': ['211', '223', '238', '239', '261', '265', '268', '270', '271', '272']}

我想在字典中创建这些值的元组列表

我用来创建的示例代码是:

for k, v in d.items():
#print(list(zip(v[::1], v[1::2])))

if len(v) == 5:
it = iter(v)
print(len(v))
print(v)
print(list(zip(it, it)))

产生

['218', '273', '275', '306', '328']
[('218', '273'), ('275', '306')]

但我理想的想要的是:

[('218', '273'), ('273', '275'), ('275', '306'), ('306', '328')]

这次迭代我错过了什么?我用它作为说明,但我希望能够使用 len(v)==1 获取字典值,例如 '190': ['229'] 也会产生 ('229',) 。如果len(v)==1很难实现,我可以给len(v)>1建议。

最佳答案

这似乎是你所要求的:

适用于所有情况

理解:

result = {}

for k, v in d.items():
indexes = [i for i, b in enumerate(v)]
result[k] = [(v[i], v[i + 1]) for i in indexes[:-1]] if len(v) > 1 else [(v[0],)]

print(result)

或者只是 if - else:

result = {}

for k, v in d.items():
indexes = [i for i, b in enumerate(v)]
if len(v) > 1:
result[k] = [(v[i], v[i + 1]) for i in indexes[:-1]]
else:
result[k] = [(v[0],)]

print(result)

对于您的情况(==5):

result = {}

for k, v in d.items():
indexes = [i for i, b in enumerate(v)]
if len(v) == 5:
result[k] = [(v[i], v[i + 1]) for i in indexes[:-1]]

print(result)

关于python - 从字典中不等长度的元素形成元组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59416197/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com