您可以使用如下函数来实现:
def match_date(l, d):
return list(filter(lambda x: x[0] == d, l))[0]
由于filter() 内置函数,它将匹配作为列表每个元素的第一个参数给出的函数,并返回一个列表,其中包含函数返回True 的所有值。因此,它将返回列表中匹配的所有日期的列表:
>>> def match_date(l, d):
... return list(filter(lambda x: x[0] == d, l))[0]
...
>>> abc = [['date1','number1'],['date2','number2']]
>>> match_date(abc, 'date2')
['date2', 'number2']
>>> abc = [['date1','number1'],['date2','number2'],['date2', 'number3'],['date3', 'number4']]
>>> match_date(abc, 'date2')
['date2', 'number2'], ['date2', 'number3']
从那里,你可以做到:
>>> abc.index(match_date(abc, 'date2')[0])
1
这将为您提供第一个匹配的元组的索引。我认为您不需要第二个索引,因为您知道它始终是 [0],因为它是您的数据模型。
让它成为一个功能:
>>> def get_index_of_match_date(l, d):
... return l.index(filter(lambda x: x[0] == d, l)[0])
...
>>> get_index_of_match_date(abc, 'date2')
0
>>> get_index_of_match_date(abc, 'date2')
1
>>> get_index_of_match_date(abc, 'date3')
3