Python 中检查一个项目是否是列表中的最后一个

ython 中要检查一个项目是否是列表中的最后一个:

  1. 使用枚举函数获取索引和项目的元组。
  2. 使用 for 循环迭代枚举对象。
  3. 如果当前索引等于列表的长度减 1,则它是列表中的最后一项。
my_list = ['a', 'b', 'c', 'd']

for index, item in enumerate(my_list):
    if index == len(my_list) - 1:
        print(item, 'is last in the list ✅')
    else:
        print(item, 'is NOT last in the list ❌')


print('--------------------------')

if 'd' == my_list[-1]:
    print('d is last in the list ✅')

print('--------------------------')

result = '_'.join(my_list)
print(result)  # ?️ 'a_b_c_d'

Python 中检查一个项目是否是列表中的最后一个

我们使用 enumerate() 函数来获取可以迭代的枚举对象。

enumerate 函数接受一个可迭代对象并返回一个包含元组的枚举对象,其中第一个元素是索引,第二个是项目。

my_list = ['a', 'b', 'c', 'd']

# 👇️ [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]
print(list(enumerate(my_list)))

我们使用 for 循环遍历枚举对象,并在每次迭代中检查当前索引是否等于列表中的最后一个索引。

my_list = ['a', 'b', 'c', 'd']

for index, item in enumerate(my_list):
    if index == len(my_list) - 1:
        print(item, 'is last in the list ✅')
    else:
        print(item, 'is NOT last in the list ❌')

Python 索引是从零开始的,所以列表中的第一个索引是 0,最后一个索引是 len(my_list) - 1

我们还可以使用不等于 != 运算符检查该项目是否不是列表中的最后一项。

my_list = ['a', 'b', 'c', 'd']

for index, item in enumerate(my_list):
    if index != len(my_list) - 1:
        print(item, 'is NOT last in the list ❌')
    else:
        print(item, 'is last in the list ✅')

如果当前迭代的项目不是列表中的最后一项,则 if 块运行。 else 块是可选的。

或者,我们可以迭代排除最后一个元素的列表片段。

my_list = ['a', 'b', 'c', 'd']

# 👇️ get a slice of the list without the last item
for item in my_list[:-1]:
    print(item, 'is NOT last in the list ❌')

print(my_list[-1], 'is last in the list ✅')

my_list[:-1] 语法返回排除最后一个元素的列表的一部分。

列表切片的语法是 my_list[start:stop:step]

示例中的切片从索引 0 开始,一直到但不包括列表中的最后一项。

我们还可以直接检查值是否等于列表中的最后一项。

my_list = ['a', 'b', 'c', 'd']


if 'd' == my_list[-1]:
    print('d is last in the list ✅')

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

如果我们需要使用特定字符串连接列表中的项目,但不想在最后一个项目之后添加字符串,请使用 str.join() 方法。

my_list = ['a', 'b', 'c', 'd']


result_1 = '_'.join(my_list)
print(result_1)  # 👉️ 'a_b_c_d'


result_2 = ' '.join(my_list)
print(result_2)  # 👉️ 'a b c d'

str.join 方法将一个可迭代对象作为参数并返回一个字符串,该字符串是可迭代对象中字符串的串联。

请注意 ,如果可迭代对象中有任何非字符串值,该方法会引发 TypeError

如果我们的列表包含数字或其他类型,请在调用 join() 之前将所有值转换为字符串。

my_list = ['a', 1, 'b', 2, 'c']


all_strings = list(map(str, my_list))

result_1 = '_'.join(all_strings)
print(result_1)  # 👉️ 'a_1_b_2_c'


result_2 = ' '.join(all_strings)
print(result_2)  # 👉️ 'a 1 b 2 c'

调用该方法的字符串用作元素之间的分隔符。

如果我们不需要分隔符而只想将可迭代对象的元素连接到一个字符串中,请对空字符串调用 join() 方法。

my_list = ['a', 'b', 'c']