gpt4 book ai didi

python - 列表操作的列表

转载 作者:行者123 更新时间:2023-12-01 07:46:34 25 4
gpt4 key购买 nike

我的代码如下:

import itertools

lists = [[0,1], [1,2,8], [3,4], [4,2], [2,5], [5,6,7], [8,9,10,11,12]]

names = [item[0] for item in lists]
for x in lists:
del x[0]

answer = {name:set(L) for name,L in zip(names, lists)}

这给了我:

{0: {1}, 1: {2, 8}, 3: {4}, 4: {2}, 2: {5}, 5: {6, 7}, 8: {9, 10, 11, 12}}

但是我想要的是为每个条目添加先前项目的键。我想要的是拥有

{0:{1},1:{0,2,8},3:{1,4},4:{3,2} (...)}

此外,我想稍微扭转一下它,我的意思是作为一个键,我希望将我在列表中的每个数字都包含在内,例如因为我有 5:{6,7} 我也想有 6:{5,7}7:{5,6} code> 显然我不应该有任何重复。

我的问题是我怎样才能实现这个目标?

为了让自己更清楚,我想可视化以下图表:

LINK

最佳答案

我发现你不太可能想要为每个列表的所有排列创建一个字典,因为其中几个列表中有重复的数字,因此可能会创建一个所有字典的列表(其中是以下的排列)每个列表)那么你可以这样做:

from itertools import permutations

lists = [[0,1], [1,2,8], [3,4], [4,2], [2,5], [5,6,7], [8,9,10,11,12]]

answer = [{k:set(v) for k, *v in perms} for perms in map(permutations, lists)]

此对象的输出:

[{0: {1}, 1: {0}}, {1: {8, 2}, 2: {8, 1}, 8: {1, 2}}, {3: {4}, 4: {3}}, {4: {2}, 2: {4}}, {2: {5}, 5: {2}}, {5: {6, 7}, 6: {5, 7}, 7: {5, 6}}, {8: {9, 10, 11, 12}, 9: {8, 10, 11, 12}, 10: {8, 9, 11, 12}, 11: {8, 9, 10, 12}, 12: {8, 9, 10, 11}}]

否则,如果您不介意丢失一些值被覆盖,那么您可以使用这种理解

answer = {k:set(v) for perms in map(permutations, lists) for k, *v in perms}

这个的输出:

{0: {1}, 1: {8, 2}, 2: {5}, 8: {9, 10, 11, 12}, 3: {4}, 4: {2}, 5: {6, 7}, 6: {5, 7}, 7: {5, 6}, 9: {8, 10, 11, 12}, 10: {8, 9, 11, 12}, 11: {8, 9, 10, 12}, 12: {8, 9, 10, 11}}

关于python - 列表操作的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56434028/

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