[英]Finding last element index based on condition
I have a list of strings, eg 我有一个字符串列表,例如
lst = ['2', '\n', '4', '\n', '\n']
I'm trying to determine the index point of the last string element that is not '\\n'. 我试图确定不是'\\ n'的最后一个字符串元素的索引点。 In the above example the index point would be 2 as '4' is the last element whose value is not '\\n'. 在上面的示例中,索引点将为2,因为“ 4”是最后一个元素,其值不是“ \\ n”。
I can find the first occurance of '\\n' easy etc: 我发现'\\ n'的首次出现很容易,等等:
lst.index('\n')
Is there a way to find the last occurance of an element that IS NOT of a particular string char? 有没有办法找到不是特定字符串char的元素的最后出现?
You can use next
with enumerate
, then subtract the result from the length of your list: 您可以将next
与enumerate
一起使用,然后从列表的长度中减去结果:
lst = ['2', '\n', '4', '\n', '\n']
idx = len(lst) - next(i for i, val in enumerate(reversed(lst), 1) if val != '\n') # 2
Or, as proposed by @Chris_Rands, iterate backwards via a range
that counts down: 或者,按照@Chris_Rands的建议,通过递减计数的range
向后迭代:
idx = next(i for i in range(len(lst)-1, -1, -1) if lst[i] != '\n') # 2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.