如何找到包含特定元素的嵌套列表的最后一次出现的索引?

时间:2019-07-02 16:25:52

标签: python python-2.7 list

我需要(最终)在嵌套列表中的特定位置插入一个值,但是需要在嵌套列表中最后一次出现特定字符串之后才插入它...所以我需要首先找到索引最后一次发生的情况。举个例子可能更有意义(我将一概而论):

a = 'RPGAccount'

input = [['RPGAccount', 'ddi=0', 'pp=0', 'kol=0', 'sddf=1234567890', '4233f2dsfa=abc', 'igg=dev1', 'id=4g43g34b433435n35n'], ['RPGAccount', 'ddi=0', 'pp=0', 'kol=0', 'sddf=NA', '4233f2dsfa=abc', 'igg=source', 'id=4g43g34b433435n35n'], ['RPGAdditional', 'addkey=asdf', 'addvalue=false', '4233f2dsfa=abc', 'igg=dev1', 'id=4g43g34b433435n35n', 'tz=asdf'], ['RPGAdditional', 'addkey=device_id', 'addvalue=F309387C-AAF5-478D-95A2-28E9B46105C7', '4233f2dsfa=abc', 'igg=dev1', 'id=4g43g34b433435n35n', 'tz=asdf'], ['RPGAdditional', 'addkey=sdaf', 'addvalue=fixed_ap', '4233f2dsfa=abc', 'igg=dev1', 'id=4g43g34b433435n35n', 'tz=asdf’]]

b = 1

所以我需要返回索引1,因为1是列表的索引

['RPGAccount', 'ddi=0', 'pp=0', 'kol=0', 'sddf=NA', '4233f2dsfa=abc', 'igg=source', 'id=4g43g34b433435n35n']

其中包含最后一次出现的字符串“ RPGAccount”

我知道我应该做类似的事情:

for l in input:
    for l_ in l:
        if a in l_:
            print input.index[l]
        else:
            pass

解决方案:

some_list = []
for l in input:
    for l_ in l:
        if a in l_:
            some_list.append(input.index(l))
        else:
            pass
location_ = some_list[-1]
print location_

2 个答案:

答案 0 :(得分:1)

您可以这样做:

a = 'RPGAccount'
input = [['RPGAccount', 'ddi=0', 'pp=0', 'kol=0', 'sddf=1234567890', '4233f2dsfa=abc', 'igg=dev1', 'id=4g43g34b433435n35n'],
         ['RPGAccount', 'ddi=0', 'pp=0', 'kol=0', 'sddf=NA', '4233f2dsfa=abc', 'igg=source', 'id=4g43g34b433435n35n'],
         ['RPGAdditional', 'addkey=asdf', 'addvalue=false', '4233f2dsfa=abc', 'igg=dev1', 'id=4g43g34b433435n35n', 'tz=asdf'],
         ['RPGAdditional', 'addkey=device_id', 'addvalue=F309387C-AAF5-478D-95A2-28E9B46105C7', '4233f2dsfa=abc', 'igg=dev1', 'id=4g43g34b433435n35n', 'tz=asdf'],
         ['RPGAdditional', 'addkey=sdaf', 'addvalue=fixed_ap', '4233f2dsfa=abc', 'igg=dev1', 'id=4g43g34b433435n35n', 'tz=asdf']]
# Index of last sublist containing a - if not found returns -1
b = next((len(input) - i - 1 for i, lst in enumerate(reversed(input)) if a in lst), -1)
print(b)
# 1

使用循环,可以更有效地执行以下操作:

location_ = -1
for i, l in enumerate(input):
    for l_ in l:
        if a in l_:
            location_ = i
print location_
# 1

答案 1 :(得分:0)

对不起,错误很小,我已经解决了...

DeleteFile