最后一次出现不是列表中字符串的项目 - Python

Last occurance of an item that is not a string in a list - Python

我有号码列表,例如

[[0,0,0,0,0], [1,1,0,0,0], [1,0,0,0,0], [0,0,0,0,0], [1,1,1,1,0]]

我想找到每个列表中最后 1 个的索引。最左边的数字是索引 0。

列表中的项目不是字符串,所以我不能使用“.rindex”函数。

感谢您的帮助。

您可以使用 enumerate 获取 1 的每个索引并提取最后一个元素。

[[idx for idx,v in enumerate(i) if v==1][-1] if 1 in i else -1 for i in lst]
# [-1, 1, 0, -1, 3]

或者使用 str.rfind,当找不到元素时不会引发错误 returns -1.

 [''.join(map(str,i)).rfind('1') for i in lst]
# [-1, 1, 0, -1, 3]

我们可以反转列表(`list[::-1]),然后使用索引函数找到它的位置。

最后,需要使用列表长度调整索引(更正 python 中从 0 开始的索引号。

data = [[0,0,0,0,0], [1,1,0,0,0], [1,0,0,0,0], [0,0,0,0,0], [1,1,1,1,0]]

# loop through all values (the lists) in data and select their last element.

last_list = [len(i) - i[::-1].index(1) - 1  if (1 in i) else None for i in data]