【问题标题】:How to check if end of list was reached?如何检查是否到达列表末尾?
【发布时间】:2011-12-01 12:29:21
【问题描述】:

如果有一个列表,比如a=[1,2,3],并且我想查看if a[4] is null,有没有办法做到这一点,而不使用异常或断言?

【问题讨论】:

标签: python list


【解决方案1】:

len 会告诉你列表的长度。引用文档:

长度
返回对象的长度(项目数)。参数可以是序列
    (字符串、元组或列表)或映射(字典)。

当然,如果你想得到listtuplestring中的最后一个元素,因为索引是从0开始的,并且项目的长度是元素计数,a[len(a)-1]会成为最后一项。


顺便说一句,通常,访问允许数字索引(str、list、tuple 等)的对象中最后一个元素的正确方法是使用a[-1]。显然,这并不涉及len

【讨论】:

  • 访问列表、元组或字符串中最后一个元素的更简单方法:a[-1]
【解决方案2】:

这是我在 Code Fights 的一个街机挑战中应用的一种方法。

基本上,列表的结尾由以下内容定义:

  • 列表长度 - 当前索引(迭代) == 1


#!/usr/bin/python3

numbers = [1, 3, 5, 8, 10, 13, 16]

list_len = len(numbers)

for n in numbers:
    current_idx = numbers.index(n)
    print("Current Number:", numbers[current_idx])
    list_end = list_len - current_idx
    if list_end != 1:
        next_idx = current_idx + 1
        print("Next Number:   ", numbers[next_idx])
    else:
        print("End Of List!")

【讨论】:

    【解决方案3】:

    使用len

    if len(a) <= index:
       ...
    

    注意:您的问题询问如何找出“如果a[4] 为空”。 a[4] 什么都不是,这就是为什么当您尝试检查它时会得到 IndexError

    【讨论】:

      【解决方案4】:

      a[4] 在这种情况下会抛出一个IndexError 异常,这与将索引4 处的a 的值与None 进行比较不同。你可以在一个列表中拥有None 的值,如果你要比较a 的值,那么当你遇到None 时,并不意味着在列表中找不到索引。例如:

      >>> a=[1,None,2]
      >>> a[1]==None
      True
      >>> a[3]
      Traceback (most recent call last):
        File "<stdin>", line 1, in <module>
      IndexError: list index out of range
      

      由于列表是连续的并按顺序索引,因此检查索引是否在列表中的正确方法是将其与列表的len() 进行比较,但根据应用程序,还有其他方法可以解决它,例如捕获IndexError,或迭代。

      >>> for index, value in enumerate(a):
      ...     print index, value
      ... 
      0 1
      1 None
      2 2
      

      【讨论】:

        【解决方案5】:

        您可以编写一个函数,其行为类似于 dict.get() 对字典所做的:

        def listget(list_, index, default=None):
            """Return the item for index if index is in the range of the list_,
            else default. If default is not given, it defaults to None, so that
            this method never raises an IndexError."""
            if index >= len(list_) or index < -len(list_):
                return default
            else:
                return list_[index]
        

        示例用法:

        >>> names = ["Mark","Frank","James"]
        >>> listget(names, 2)
        'James'
        >>> listget(names,-3)
        'Mark'
        >>> listget(names,3) # returns None
        >>> listget(names,4,0)
        0
        

        所以它总是会返回一个值,你不会得到任何异常。

        【讨论】:

          【解决方案6】:

          您没有提供特定的用例,但通常对于列表,您会使用 len 来查看列表中有多少元素。

          if len(a) > 3:
              # Do something
          

          【讨论】:

            【解决方案7】:

            检查您当前是否正在查看列表末尾的元素(使用任何语言)的一般方法是将您正在查看的当前索引与列表长度减一进行比较(因为索引从 0 开始)。

            a[4] 并不是真正的任何东西,因为它不存在 - 某些语言可能会将其实现为 null(或未定义),但如果您尝试访问它,许多语言会简单地抛出异常。

            【讨论】:

              【解决方案8】:

              a = [1,2,3]

              a[2:3][3]

              a[3:4][ ]

              所以 a[i:i+1] != [ ] 判断是否是 a 的索引

              a[i:] 做同样的事情,但 a[i:] 创建另一个列表,可能很长,而 a[i:i+ 1] 如果不为空,则为 1 个元素

              【讨论】:

                【解决方案9】:

                这是我用来检查是否已到达列表末尾的逻辑语句:

                arr = [1,3,2,4,5]
                #counter for the array
                arr_counter = 0
                
                for ele in array:
                    # check if end of list has been reached
                    if (arr_counter+1) != len(arr):
                        #put all your code here
                        pass
                    # increment the array counter
                    arr_counter += 1
                

                希望这会有所帮助! :)

                【讨论】:

                  【解决方案10】:

                  看这里: https://www.geeksforgeeks.org/python-how-to-get-the-last-element-of-list/

                  test_list = [1, 4, 5, 6, 3, 5] 
                  # printing original list  
                  print ("The original list is : " + str(test_list)) 
                  # First naive method 
                  # using loop method to print last element  
                  for i in range(0, len(test_list)): 
                      if i == (len(test_list)-1): 
                          print ("The last element of list using loop : "+  str(test_list[i])) 
                  # Second naive method         
                  # using reverse method to print last element 
                  test_list.reverse() `enter code here`
                  print("The last element of list using reverse : "+  str(test_list[0])) 
                  

                  【讨论】:

                    猜你喜欢
                    • 1970-01-01
                    • 2022-08-03
                    • 1970-01-01
                    • 2015-05-14
                    • 2019-04-18
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 2019-12-06
                    相关资源
                    最近更新 更多