Ski*_*izo 0 python dictionary list python-2.7
我想用python编写一个在列表中找到值的程序。像这样:
arr = [1, 14, 2, 4, 5, 11, 8, 10]
for i in range(1, len(arr)):
if(i * 2 in arr):
print "!"
Run Code Online (Sandbox Code Playgroud)
我要检查的数组要更长一些,因此需要很长时间。
我想出了一个制作哈希表而不是列表的想法。像这样的东西:
arr = {1: "something", 14: "something", 2: "something", 4: "something",
5: "something", 11: "something", 8: "something", 10: "something"}
Run Code Online (Sandbox Code Playgroud)
我的想法是检查是否i等于(例如)2检查是否arr[i*2]将返回某些内容,因为这样,程序就无需查找就可以调用它(如果存在)。
问题是是否i等于,3所以它将检查是否arr[3*2]会返回某些内容,不会,因为没有键6会返回错误。
我如何用我的想法做到这一点?
注意:您所指的项目arr实际上是list在Python中调用的。而“哈希表”实际上称为字典。因此,我将将该arr对象称为dict_object。
您可以使用in运算符来检查关键字是否在字典中,
if i * 2 in dict_object:
print "!"
Run Code Online (Sandbox Code Playgroud)
该in运营商将返回True如果i * 2在字典中一个有效的密钥,False否则。
还有另一种方法可以做到这一点。字典对象具有一个称为的函数get,该函数接受在字典中找不到键时要返回的默认值。默认返回值为None。您可以None像这样使用哨兵值
if dict_object.get(i * 2) is not None:
# If the returned value is not None, then the key is present in the dictionary
print "!"
Run Code Online (Sandbox Code Playgroud)
还有另一种方法可以做到这一点。当您访问词典中没有的键时,您将得到KeyError。您可以像这样
for i in range(1, len(dict_object) + 1):
try:
if dict_object[i * 2]:
print "!"
except KeyError:
# If value of `i * 2` is not in the dictionary, we will reach here
pass
Run Code Online (Sandbox Code Playgroud)
除此之外,如果未使用存储在字典中的值(换句话说,如果您仅担心键),则可以使用set而不是字典,例如
numbers_set = {1, 14, 2, 4, 5, 11, 8, 10} # Note {..}, not [..]
if i * 2 in numbers_set:
print "!"
Run Code Online (Sandbox Code Playgroud)
如果已经有了列表,则可以将列表转换为具有如下set功能的集合
numbers_set = set([1, 14, 2, 4, 5, 11, 8, 10])
if i * 2 in numbers_set:
print "!"
Run Code Online (Sandbox Code Playgroud)
PS:您的程序中存在错误。在Python中,range函数从第一个参数开始运行,直到最后一个参数值-1。例如,
>>> range(1, 5)
[1, 2, 3, 4]
>>> range(2, 10)
[2, 3, 4, 5, 6, 7, 8, 9]
Run Code Online (Sandbox Code Playgroud)
最后的值将不包括在内。因此,您需要range像这样更改的参数
for i in range(1, len(x) + 1):
Run Code Online (Sandbox Code Playgroud)