python - 如何使用列表作为 python 字典中的键

标签 python dictionary

我想使用如下字典: 示例:{[8, 16]:[[1,2,4,8],8], [16, 24]: [[1,2,3,4,8,12], 12]}

8 和 16 是要输入的两个数字,我需要像上面那样构造一个字典。

使用 setdefault,我可以为字典中的值创建一个列表,但不能为键创建一个列表

下面是我的代码:

#!/usr/bin/env python
"""
        This Program calculates common factors between two Numbers , which 
        is stored on a list and also greatest common factor is also computed.
        All this is stored in a dictionary
        Example: { '[n1, n2]': [[Commonfac1(n1,n2), Commonfac2(n1,n2)....Commonfacn(n1,n2)],GreatestCommonFactor] }
"""
def Factors(number):
        result = []
        for i in range(1, number+1):
                if (number % i) == 0:
                        result.append(i)

        return result

def Common_Factors(n1, n2):
        result = []
        for element in n1:
                if element in n2:
                        result.append(element)

        return result

def greatest_common_factor(common_factors):
        count = 0
        length = len(common_factors)
        current_largest = common_factors[count]
        for i in common_factors:
                count += 1
                if count <= length -1:
                        if current_largest < common_factors[count]:
                                current_largest = common_factors[count]
        return current_largest


def main():
        n1 = 8
        n2 = 16
        result1 = Factors(n1)
        result2 = Factors(n2)

        CF = Common_Factors(result1, result2)

        GCF = greatest_common_factor(CF)

        dict = {}

        dict.setdefault([n1, n2], []).append(CF)
        print dict

if __name__ == '__main__':
        main()

当我运行上面的程序时,出现以下错误:

$ python math74.py 
Traceback (most recent call last):
  File "math74.py", line 58, in <module>
    main()
  File "math74.py", line 54, in main
    dict.setdefault([n1, n2], []).append(CF)
TypeError: unhashable type: 'list'

有关我如何实现上述目标的任何提示。 ?

进一步说明: {[8, 16]:[[1,2,4,8],8], [16, 24]: [[1,2,3,4,8,12], 12]}

8、16 是两个数字,将由用户输入,1、2、4、8 是公因数,8 是最大公因数。

最佳答案

列表可能不是您想要的,因为: 1. 列表是可变的。这意味着它可以更改(删除/添加/修改)它的值。例如:

>>> testList = [1,5]
>>> d = {"myList": testL}
>>> d
{'myList': [1, 5]}
>>> testList.append(53)
>>> d
{'myList': [1, 5, 53]}
>>> 

如您所见,列表可以更改,键需要是唯一的。
对于不可变的数组类型,Python 有一个元组。一旦你定义了一个元组,它就不能被修改。这意味着,您也可以将其用作目录中的键:

>>> myTuple = (4, 5)
>>> myDict = {myTuple: "here is the value"}
>>> myDict
{(4, 5): 'here is the value'}
>>> myTuple.append(9)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'append'

关于python - 如何使用列表作为 python 字典中的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25343089/

相关文章:

python - 在根路径中获取最新目录

Python初学者递归

android - map 不显示路况信息

Python matplotlib 绘制具有多个值的字典

python映射字典到数组

c++ - 如何将 2 个 char* 数组直接映射到 std::map<std::string,std::string>

Python将列表分成具有重复的 block

python - 如何在多个 Django 模型上进行 JOIN

python - 如何将模块添加到 Anaconda

c# - 代码字典查找的更好方法?