Python:用于存储模式及其结果的字典

时间:2014-05-07 18:47:31

标签: python dictionary

我遇到了一个问题,我需要存储一些模式和它的匹配。 我希望有类似下面的内容

dict1={}
a=range(1,11)
dict1["range1-11"]=a

但是,它低于错误。

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not str

我其实在寻找

dict1["range-1-11"] to print
[1,2,3,4,5,6,7,8,9,10]

当然可能:)

有人可以帮助我吗

3 个答案:

答案 0 :(得分:2)

你有什么应该为python 2.x工作得很好。对于python3,您需要更改它:

dict1 = {}
a = list(range(1,11))
dict1["range1-11"] = a

更容易扩展将分解开始和停止,如下所示:

ranges = ((1, 11),)
dict1 = {'range{}-{}'.format(a, b): list(range(a, b)) for a, b in ranges}

答案 1 :(得分:0)

实际上这有些不对劲。下面的东西很完美

>>>
>>> dict1={} 
>>> a=range(1,11)
>>> dict1["range1-11"]=a
>>> dict1["range1-11"]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> b=range(11,21)
>>> b
[11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
>>> dict1["range11-21"]=b
>>> dict1["range11-21"]
[11, 12, 13, 14, 15, 16, 17, 18, 19, 20]

全部谢谢

答案 2 :(得分:-2)

你问的问题有点不清楚,但你可能想要这样的东西:

dict1 = {}
a = "range(1,11)"
dict1[a] = eval(a)