0

我尝试使用 'in' 和 has_key(),但如果键不是单个值,这些似乎不起作用:

 >>> aarr["x","y","z"]=1
 >>> aarr["x","y","z"]
 1
 >>> if "x","y","z" in aarr:
   File "<stdin>", line 1
     if "x","y","z" in aarr:
           ^
 SyntaxError: invalid syntax
 >>> aarr.has_key("x","y","z")
 Traceback (most recent call last):
  File "<stdin>', line 1, in <module>
 TypeError: has_key() takes exactly one argument (3 given)

尝试aarr.has_key(["x","y","z"])或者如果["x","y","z"] in aarr:在这两种情况下都抱怨unhashable type: 'list'.

4

1 回答 1

6

在表达式中使用逗号时,您正在创建一个元组。

使用元组进行测试:

if ("x","y","z") in aarr:

你也可以看看.keys()学习这个:

>>> aarr = {}
>>> aarr["x","y","z"]=1
>>> if ("x","y","z") in aarr:
...     print 'success!'
... 
success!
>>> aarr.keys()
[('x', 'y', 'z')]
>>> aarr.keys()[0]
('x', 'y', 'z')
于 2012-12-31T20:29:42.943 回答