Section 71.1: 搜索一个元素
Python 中的所有内置集合都使用 in 实现了一种检查元素成员是否存在的方法。
List
alist = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
5 in alist # True
10 in alist # False
Tuple
atuple = ('0', '1', '2', '3', '4')
4 in atuple # False
'4' in atuple # True
String
astring = 'i am a string'
'a' in astring # True
'am' in astring # True
'I' in astring # False
Set
aset = {(10, 10), (20, 20), (30, 30)}
(10, 10) in aset # True
10 in aset # False
Dict
dict 有点特殊:普通的 in 只检查键。如果要搜索值,则需要指定。如果要搜索键值对,情况也一样。
adict = {0: 'a', 1: 'b', 2: 'c', 3: 'd'}
1 in adict # True - implicitly searches in keys
'a' in adict # False
2 in adict.keys() # True - explicitly searches in keys
'a' in adict.values() # True - explicitly searches in values
(0, 'a') in adict.items() # True - explicitly searches key/value pairs

Section 71.2: 在自定义类中搜索:__contains__ and __iter__
为了允许在自定义类中使用 in,类必须提供神奇的方法 __contains__,否则就必须提供 __iter__-方法。
假设你有一个包含列表的类:
class ListList:
def __init__(self, value):
self.value = value
# 创建所有数值的集合,以便快速访问
self.setofvalues = set(item for sublist in self.value for item in sublist)
def __iter__(self):
print('Using __iter__.')
# 所有子列表元素的生成器
return (item for sublist in self.value for item in sublist)
def __contains__(self, value):
print('Using __contains__.')
# 只需查找值是否在集合中
return value in self.setofvalues
# 即使没有集合,也可以使用 iter 方法进行包含检查:
# return any(item == value for item in iter(self))
使用 in 可以进行成员测试:
a = ListList([[1,1,1],[0,1,1],[1,5,1]])
10 in a # False
# Prints: Using __contains__.
5 in a # True
# Prints: Using __contains__.
即使删除了 __contains__ 方法:
del ListList.__contains__
5 in a # True
# Prints: Using __iter__.
注意:即使类实现了 __contains__ 方法,循环(如 for i in a 中)将始终使用 __iter__。

Section 71.3: 获取字符串的索引:str.index()、str.rindex() 和 str.find()、str.rfind()
字符串也有索引方法,但还有更多高级选项和附带了 str.find。这两种方法都有一个它们自己互补的反转方法。

astring = 'Hello on StackOverflow'
astring.index('o') # 4
astring.rindex('o') # 20
astring.find('o') # 4
astring.rfind('o') # 20
index/rindex 与 find/rfind 的区别在于,如果在字符串中找不到子串,会发生什么情况:
astring.index('q') # ValueError: substring not found
astring.find('q') # -1
所有这些方法都允许起始和结束索引:
astring.index('o', 5) # 6
astring.index('o', 6) # 6 - start is inclusive
astring.index('o', 5, 7) # 6
astring.index('o', 5, 6) # - end is not inclusive
# ValueError: substring not found
astring.rindex('o', 20) # 20
astring.rindex('o', 19) # 20 - still from left to right
astring.rindex('o', 4, 7) # 6

Section 71.4: 获取索引列表和元组:list.index(), tuple.index()
list 和 tuple 都有一个索引方法来获取元素的位置:
alist = [10, 16, 26, 5, 2, 19, 105, 26]
# search for 16 in the list
alist.index(16) # 1
alist[1] # 16
alist.index(15)
# ValueError: 15 is not in list
但只会返回第一个找到的元素的位置:
atuple = (10, 16, 26, 5, 2, 19, 105, 26)
atuple.index(26) # 2
atuple[2] # 26
atuple[7] # 26 - is also 26!

Section 71.5: 在二进制文件中搜索键值
dict 没有搜索值或键的内置方法,因为字典是无序的。您可以创建一个函数来获取指定值的键(或多个键):
def getKeysForValue(dictionary, value):
foundkeys = []
for key in dictionary:
if dictionary[key] == value:
foundkeys.append(key)
return foundkeys
这也可以写成等价的列表理解:
def getKeysForValueComp(dictionary, value):
return [key for key in dictionary if dictionary[key] == value]
如果您只关心一个找到的键:
def getOneKeyForValue(dictionary, value):
return next(key for key in dictionary if dictionary[key] == value)

前两个函数将返回具有指定值的所有键的列表:
adict = {'a': 10, 'b': 20, 'c': 10}
getKeysForValue(adict, 10) # ['c', 'a'] - order is random could as well be ['a', 'c']
getKeysForValueComp(adict, 10) # ['c', 'a'] - dito
getKeysForValueComp(adict, 20) # ['b']
getKeysForValueComp(adict, 25) # []
另一个只会返回一个键:
getOneKeyForValue(adict, 10) # 'c' - depending on the circumstances this could also be 'a'
getOneKeyForValue(adict, 20) # 'b'
并在值不在 dict 中时引发 StopIteration-Exception 异常:
getOneKeyForValue(adict, 25)
# StopIteration

Section 71.6: 获取排序序列的索引: bisect.bisect_left()
排序序列允许使用更快的搜索算法:bisect.bisect_left()1:
import bisect
def index_sorted(sorted_seq, value):
"""Locate the leftmost value exactly equal to x or raise a ValueError"""
i = bisect.bisect_left(sorted_seq, value)
if i != len(sorted_seq) and sorted_seq[i] == value:
return i
raise ValueError
alist = [i for i in range(1, 100000, 3)] # Sorted list from 1 to 100000 with step 3
index_sorted(alist, 97285) # 32428
index_sorted(alist, 4) # 1
index_sorted(alist, 97286)
# ValueError

对于非常大的排序序列,速度增益可能相当高。以第一次搜索为例,速度大约提高了 500 倍:
% timeit index_sorted(alist, 97285)
# 100000 loops, best of 3: 3 μs per loop
% timeit alist.index(97285)
# 1000 loops, best of 3: 1.58 ms per loop
如果该元素是最早出现的元素之一,则速度会慢一些:
% timeit index_sorted(alist, 4)
# 100000 loops, best of 3: 2.98 μs per loop
% timeit alist.index(4)
# 1000000 loops, best of 3: 580 ns per loop
Section 71.7: 搜索嵌套序列
在嵌套序列(如list和tuple)中搜索时,需要使用类似在dict中搜索键值的方法,但需要自定义函数。
如果值是在序列中找到的,则是最外层序列的索引:
def outer_index(nested_sequence, value):
return next(index for index, inner in enumerate(nested_sequence)
for item in inner
if item == value)
alist_of_tuples = [(4, 5, 6), (3, 1, 'a'), (7, 0, 4.3)]
outer_index(alist_of_tuples, 'a') # 1
outer_index(alist_of_tuples, 4.3) # 2

或外序列和内序列的索引:
def outer_inner_index(nested_sequence, value):
return next((oindex, iindex) for oindex, inner in enumerate(nested_sequence)
for iindex, item in enumerate(inner)
if item == value)
outer_inner_index(alist_of_tuples, 'a') # (1, 2)
alist_of_tuples[1][2] # 'a'
outer_inner_index(alist_of_tuples, 7) # (2, 0)
alist_of_tuples[2][0] # 7

一般来说(并不总是),使用 next 和带条件的生成器表达式来查找搜索值的首次出现是最有效的方法。