新手的列表方法队列

我知道有一种查找和重新查找字符串的方法.对于列表,我只知道索引方法.A'rindex'方法类似于字符串的rfind方法吗?

# 回答1


不是真的,但你可以想办法绕过它.例如,您可以使用列表的反向方法,然后执行index()搜索,然后重新反转列表.
# 回答2


您可以创建一个函数来返回最后一个索引号.

选择 | 换行 | 行号
  1. def rindex(s, item):
  2.     """
  3.     Return the index of the last occurrence of 'item' in string/list 's'.
  4.     Return False if 'item' is not in 's'.
  5.     """
  6.     i=0
  7.     while True:
  8.         try:
  9.             i = s.index(item, i)
  10.             i += 1
  11.         except:
  12.             return i-1
  13.     return False

测试:

选择 | 换行 | 行号
  1. >>> rindex([1,2,3,4,5,6,5,4,3,2,1,2,3,4,3,2,1], 3)
  2. 14
  3. >>> 
# 回答3


嗯……那个功能不起作用.我得研究研究.不管怎样,谢谢你
# 回答4


为什么会这样呢?
这是否会导致错误,或者您是在说您的问题有其他意思?
# 回答5


当我尝试使用该函数时,即使我知道项在字符串中,它也返回FALSE
# 回答6


不知何故,它现在起作用了...让你看看我知道多少.:)
谢谢你的帮助.

标签: python

添加新评论