python字典的键可以用列表吗_如何在python字典中使用列表作为键

我想使用如下字典:

示例:{[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

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是最大公因数.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值