不要与 this question in Stackoverflow 混淆.
我有一个名为 a = [2, 3, 4, 1]
我有一些函数,比如 func(),如下所示:
def func(a):
o = []
n = len(a)
for i in range(n):
x=a[:]
x[i],x[(i+1)%n] = x[(i+1)%n],x[i]
o.append(x)
return o
并且 func(a) 生成另一个列表,如下所示:
[[3, 2, 4, 1], [2, 4, 3, 1], [2, 3, 1, 4], [1, 3, 4, 2]]
现在我想将输出列表映射到生成它的列表。那么,如何生成如下格式的字典:
a : o
key : value1, value2........last value
[2, 3, 4, 1] : [3, 2, 4, 1], [2, 4, 3, 1], [2, 3, 1, 4], [1, 3, 4, 2]
最佳答案
字典中的键不能是可变类型。你可以用一个元组来代替。那就是
(2, 3, 4, 1) : [3, 2, 4, 1], [2, 4, 3, 1], [2, 3, 1, 4], [1, 3, 4, 2]
这可以这样做
def func(a):
o = []
n = len(a)
for i in range(n):
x=a[:]
x[i],x[(i+1)%n] = x[(i+1)%n],x[i]
o.append(x)
return {tuple(a):o}
例如 func([2,3,4,1])
现在将返回
{(2, 3, 4, 1): [[3, 2, 4, 1], [2, 4, 3, 1], [2, 3, 1, 4], [1, 3, 4, 2]]}
另请注意:根据 documentation :
The only types of values not acceptable as keys are values containing lists or dictionaries or other mutable types that are compared by value rather than by object identity, the reason being that the efficient implementation of dictionaries requires a key’s hash value to remain constant
发表评论编辑
您可以使用 []
表示法直接访问 key 。
例如:
l = [2,3,4,1]
a = func(l)
print (a[tuple(l)])
这将打印值列表。
或者你可以循环遍历整个字典
for i in a.items():
for j in i:
print (j)
这将打印
[3, 2, 4, 1]
[2, 4, 3, 1]
[2, 3, 1, 4]
[1, 3, 4, 2]
关于python - 映射列表 - python 中的列表作为字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27660431/