索引列表列表

时间:2015-03-08 15:42:14

标签: python indexing nested-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)

OR

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

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

2 个答案:

答案 0 :(得分:0)

您可以使用以下功能实现:

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

答案 1 :(得分:0)

def firstMatch (date, lst):
    for i, sublist in enumerate(lst):
        if sublist[0] == date:
            return i

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

>>> 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
相关问题