Python 如何查找包含特定元素的嵌套列表最后一次出现的索引?
我需要(最终)在嵌套列表中的特定位置插入一个值,但它需要在嵌套列表中某个特定字符串的最后一次出现之后插入…因此我需要首先找到最后一次出现的索引。举个例子可能更有意义(我将概括): 所以我需要返回一个索引1,因为1是列表的索引Python 如何查找包含特定元素的嵌套列表最后一次出现的索引?,python,python-2.7,list,Python,Python 2.7,List,我需要(最终)在嵌套列表中的特定位置插入一个值,但它需要在嵌套列表中某个特定字符串的最后一次出现之后插入…因此我需要首先找到最后一次出现的索引。举个例子可能更有意义(我将概括): 所以我需要返回一个索引1,因为1是列表的索引 ['RPGAccount', 'ddi=0', 'pp=0', 'kol=0', 'sddf=NA', '4233f2dsfa=abc', 'igg=source', 'id=4g43g34b433435n35n'] 其中包含字符串“RPGAccount”的最后一次出现
['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_
对不起,这个错误很小,我解决了
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_
您可以这样做:
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
location_ = -1
for i, l in enumerate(input):
for l_ in l:
if a in l_:
location_ = i
print location_
# 1