索引列表列表

Index a list of lists

很抱歉用这个可能很愚蠢的问题打扰你,但我已经(再一次)被困在这个问题上一段时间了。

我有列表列表

abc = [['date1','number1'],['date2','number2']...]

日期可能相同。例如:date1 和 date2 可能都是“02/02/2015”,而 date3 可能是“05/02/2015”。

在执行示例时,我想获取元素的索引,其中日期与我提供函数的日期第一次匹配。例如,类似

function(abc,'02/02/2015')
output: [0][0] (and only this, so not [1][0] as well)

function(abc,'05/02/2015')
output: [2][0]

有人知道怎么做吗?谢谢!

您可以使用如下函数实现:

def match_date(l, d):
    return list(filter(lambda x: x[0] == d, l))[0]

多亏了 filter() 内置函数,它将匹配作为列表每个元素的第一个参数给出的函数,并且 return 一个包含函数 [=29] 的所有值的列表=]ed True。因此,它将 return 列表中匹配的所有日期的列表:

>>> 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
def firstMatch (date, lst):
    for i, sublist in enumerate(lst):
        if sublist[0] == date:
            return i

本质上,您想遍历列表并检查每个子列表的第一个元素是否与您想要的日期匹配。如果是这样,只需 return 您当前所在的索引;否则继续迭代。

>>> abc = [['02/02/2015', '1'], ['02/02/2015', '2'], ['05/02/2015', '3']]    
>>> firstMatch('02/02/2015', abc)
0
>>> firstMatch('05/02/2015', abc)
2