【问题标题】:Last occurance of an item that is not a string in a list - Python列表中不是字符串的项目的最后一次出现 - Python
【发布时间】:2020-09-08 00:31:45
【问题描述】:

我有数字列表的列表,例如

[[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”函数。

感谢您的帮助。

【问题讨论】:

  • [0,0,0,0,0] 这里面没有1 这会是什么输出
  • 我只需要一个占位符 -1 甚至可以是一个字符串“null”。

标签: python list indexing ironpython


【解决方案1】:

您可以使用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,它不会在找不到元素时引发错误,它会返回-1

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

【讨论】:

  • 谢谢,我使用了你建议的第一个解决方案。
  • @sjmurphy84 很高兴为您提供帮助;)
【解决方案2】:

我们可以反转列表(`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] 

【讨论】:

    猜你喜欢
    • 2016-03-30
    • 1970-01-01
    • 2011-10-16
    • 2011-04-19
    • 1970-01-01
    • 2014-08-22
    • 2012-03-17
    • 2011-07-26
    相关资源
    最近更新 更多