我正在使用以下形式填充的列表:
tups = [(1, 2, 4.56), (2, 1, 1.23), (1, 3, 2.776), ...]
我想执行两项操作。
第一个是查找以 n 编号开头的所有元组,例如:
def starting_with(n, tups):
'''Find all tuples with tups that are of the form (n, _, _).'''
# ...
第二个是相反的,找到第二个值 n 的所有元组:
def middle_with(n, tups):
'''Find all tuples with tups that are of the form (_, n, _).'''
# ...
从某种意义上说,在元组列表上进行模式匹配。我如何在Python中执行此操作?
答案 0 :(得分:5)
使用列表理解:
>>> tups = [(1, 2, 4.56), (2, 1, 1.23), (1, 3, 2.776)]
>>> [t for t in tups if t[0] == 1] # starting_with 1
[(1, 2, 4.56), (1, 3, 2.776)]
>>> [t for t in tups if t[1] == 3] # (_, 3, _)
[(1, 3, 2.776)]
ALTERNATIVE :使用与任意数字匹配的对象。 (__eq__
)
>>> class AnyNumber(object):
... def __eq__(self, other):
... return True
... def __ne__(self, other):
... return False
...
>>> ANY = AnyNumber()
>>> ANY == 0
True
>>> ANY == 1
True
>>> tups = [(1, 2, 4.56), (2, 1, 1.23), (1, 3, 2.776)]
>>> [t for t in tups if t == (1, ANY, ANY)]
[(1, 2, 4.56), (1, 3, 2.776)]
>>> [t for t in tups if t == (ANY, 1, ANY)]
[(2, 1, 1.23)]
答案 1 :(得分:0)
def starting_with(n, tups):
'''Find all tuples with tups that are of the form (n, _, _).'''
return [t for t in tups if t[0] == n]