获取 List 的第 N 个元素(如果它存在于 Python 中)

目录

Get the Nth element of a List if it exists in Python

  1. 获取 List 的第 N 个元素(如果它存在于 Python 中)
  2. 使用三元运算符获取 List 的第 N 个元素(如果存在)
  3. 检查列表中的第 N 个元素是否存在于 Python 中

获取 List 的第 N 个元素(如果它存在于 Python 中)

获取列表的第 N 个元素(如果存在):

  1. 使用try/except语句获取指定索引处的列表元素。
  2. 如果IndexError引发 an,则返回默认值。
  3. 否则,返回指定索引处的列表元素。
主程序
def get_nth_element(li, index, default_value=None): try: return li[index] except IndexError: return default_value my_list = ['bobby', 'hadz', 'com'] print(get_nth_element(my_list, 1)) # 👉️ hadz print(get_nth_element(my_list, 100)) # 👉️ None print(get_nth_element(my_list, 100, 'default')) # 👉️ default print(get_nth_element(my_list, -1)) # 👉️ com

该函数采用列表、索引和可选的默认值,如果索引超出范围,则使用默认值。

try语句中,我们尝试访问指定索引处的列表。

如果索引超出范围,IndexError则引发 an 并except运行块。

主程序
my_list = ['bobby', 'hadz', 'com'] # ⛔️ IndexError: list index out of range print(my_list[100])

如果列表中不存在指定的索引,则返回默认值。

默认值设置为,None除非用户在函数调用中提供第三个参数。
主程序
def get_nth_element(li, index, default_value=None): try: return li[index] except IndexError: return default_value my_list = ['bobby', 'hadz', 'com'] print(get_nth_element(my_list, 100)) # 👉️ None print(get_nth_element(my_list, 100, 'default')) # 👉️ default

该函数返回列表的第 N 个元素(如果存在),否则返回默认值。

或者,您可以使用三元运算符。

使用三元运算符获取列表的第 N 个元素(如果存在)

获取列表的第 N 个元素(如果存在):

  1. 检查列表中是否存在提供的索引。
  2. 如果索引存在于列表中,则返回指定索引处的列表元素。
  3. 如果列表中不存在该索引,则返回提供的默认值。
主程序
def get_nth_element(li, index, default_value=None): return li[index] if -len(li) <= index < len(li) else default_value my_list = ['bobby', 'hadz', 'com'] print(get_nth_element(my_list, 1)) # 👉️ hadz print(get_nth_element(my_list, 100)) # 👉️ None print(get_nth_element(my_list, 100, 'default')) # 👉️ default print(get_nth_element(my_list, -1)) # 👉️ com

我们使用了三元运算符,它基本上是一个内联if/else语句。

if语句检查列表的长度是否大于指定的索引。

Python 索引是从零开始的,因此列表中的第一项的索引为,最后一项的索引为 0-1 len(my_list) - 1

我们还检查列表的否定长度是否小于或等于指定的索引。

这对于处理负指数是必要的,例如-10.

如果列表的长度为3,则列表中最大的负索引为-3

换句话说,列表中最大的负索引等于 -len(my_list)

负索引可用于向后计数,例如my_list[-1]返回列表中的最后一项并my_list[-2]返回倒数第二项。

如果您不必使用负索引,则可以稍微简化该功能。

主程序
def get_nth_element(li, index, default_value=None): return li[index] if index < len(li) else default_value my_list = ['bobby', 'hadz', 'com'] print(get_nth_element(my_list, 1)) # 👉️ hadz print(get_nth_element(my_list, 100)) # 👉️ None print(get_nth_element(my_list, 100, 'default')) # 👉️ default

if语句只是检查索引是否存在于列表中。

如果满足条件,我们将返回指定索引处的列表项。

如果不满足条件,我们将返回默认值。

检查 List 中的第 N 个元素是否存在于 Python 中

检查列表中的第 N 个元素是否存在:

  1. 使用len()函数获取列表的长度。
  2. 检查列表的长度是否大于或等于 N。
  3. 如果满足条件,则列表中的第 N 个元素存在。
主程序
my_list = ['bobby', 'hadz', 'com'] # ✅ check if Nth element in list exists if len(my_list) >= 3: # 👇️ The list has a length of at least 3 elements | com print('The list has a length of at least 3 elements', my_list[2]) else: print('The list has a length of less than 3') # ----------------------------------------------------- # ✅ get Nth element in list without getting an error if not present def get_nth_element(li, index, default_value=None): try: return li[index] except IndexError: return default_value my_list = ['bobby', 'hadz', 'com'] print(get_nth_element(my_list, 1)) # 👉️ hadz print(get_nth_element(my_list, 50)) # 👉️ None print(get_nth_element(my_list, 50, 'default')) # 👉️ default

第一个示例使用列表的长度来检查第 N 个元素是否存在。

If the list has a length of 3, then there are 3 elements in the list.

If there are 3 elements in the list, the last element has an index of 2.

Python indexes are zero-based, so the first item in a list has an index of 0, and the last item has an index of -1 or len(my_list) - 1.

Since indexes are zero-based, the last item in a list will always have an index
of len(my_list) - 1.

If you need to get the Nth element in a list if it exists, without getting an
error, use a try/except statement.

main.py
def get_nth_element(li, index, default_value=None): try: return li[index] except IndexError: return default_value my_list = ['bobby', 'hadz', 'com'] print(get_nth_element(my_list, 1)) # 👉️ hadz print(get_nth_element(my_list, 50)) # 👉️ None print(get_nth_element(my_list, 50, 'default')) # 👉️ default

The function takes a list, an index and optionally a default value which is used
if the index is out of range.

In the try statement, we try to access the list at the specified index.

If the index is out of range, an IndexError is raised and the except block
runs.

main.py
my_list = ['bobby', 'hadz', 'com'] # ⛔️ IndexError: list index out of range print(my_list[50])

If the specified index doesn’t exist in the list, we return the default value.

The default value is set to None unless the user provides a third argument in the call to the function.

The function returns the Nth element of the list if it exists, otherwise a
default value is returned.

The function also works with negative indexes.

main.py
def get_nth_element(li, index, default_value=None): try: return li[index] except IndexError: return default_value my_list = ['bobby', 'hadz', 'com'] print(get_nth_element(my_list, -2)) # 👉️ hadz print(get_nth_element(my_list, -50)) # 👉️ None print(get_nth_element(my_list, -50, 'default')) # 👉️ default
Negative indices can be used to count backward, e.g. my_list[-1] returns the last item in the list and my_list[-2] returns the second to last item.

If the list has a length of 3, the largest negative index in the list is -3.

In other words, the largest negative index in a list is the negated length of
the list.