加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-20 11:37:20 所属栏目:Python 来源:网络整理
导读:我想使用如下字典: 示例:{[8,16]:[[1,2,4,8],[16,24]:[[1,3,8,12],12]} 8和16是将要输入的两个数字,我需要构建如上所述的字典. 使用setdefault,我可以在字典中创建值列表,但不能为键创建列表 以下是我的代码: #!/usr/bin/env python""" This Program ca
我想使用如下字典:
示例:{[8,16]:[[1,2,4,8],[16,24]:[[1,3,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,[]).append(CF)
TypeError: unhashable type: 'list'

关于我如何实现上述任何提示. ?

澄清更多:
{[8,12]}

8,16是两个数字,它们是用户输入,1,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'

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读