python - 映射列表 - python 中的列表作为字典

标签 python list dictionary

不要与 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/

相关文章:

python - 使用 pyspark 时 dill 和 pickle 之间的冲突

c# - 按值而非引用将 List<T> 分配给另一个 List<T>

python - 检查 Python 字典中列表中的重复元素

python - 如何更好地使用 Polars 中的 apply?

python - 使用 Selenium 和 Python 在日历日期选择器中选择特定日期

Python - 向时间序列数据集添加行

java - Java 中的链接按钮和文本字段数组

python - 如何将元组作为函数的参数传递

python - 更改列表中具有相同键的字典的值

python - 将结构化的条目字典解析为美化的 Excel 工作表