Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/288.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:用于存储模式及其结果的字典_Python_Dictionary - Fatal编程技术网

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

Python:用于存储模式及其结果的字典,python,dictionary,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={}
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 = {}
a = "range(1,11)"
dict1[a] = eval(a)

对于Python2.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}

实际上是出了什么问题。下面的事情很完美

>>>
>>> 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]

谢谢大家

您能展示一下您想要的输出吗?目前还不清楚你在问什么。你所说的“看起来这是不可能的”是什么意思?追踪?当前结果与预期结果?“类型错误:列表索引必须是整数,而不是str”-请显示实际代码。。无论如何,我会创建一个自定义哈希/可比较类型来表示这些范围/模式,然后可以将其用作键。谢谢。这很有效。我想我做错了什么。
>>>
>>> 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]