检测项目是否为列表中的最后一个 [英] Detect If Item is the Last in a List

查看:68
本文介绍了检测项目是否为列表中的最后一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Python 3,并尝试检测某项是否是列表中的最后一项,但有时会重复.这是我的代码:

I am using Python 3, and trying to detect if an item is the last in a list, but sometimes there will repeats. This is my code:

a = ['hello', 9, 3.14, 9]
for item in a:
    print(item, end='')
    if item != a[-1]:
        print(', ')

我想要这个输出:

hello,
9,
3.14,
9

但我得到以下输出:

hello, 
93.14, 
9

我理解为什么我得到了我不想要的输出. 我希望仍然可以使用循环,但是我可以解决它们. (我想将其与更复杂的代码一起使用)

I understand why I am getting the output I do not want. I would prefer if I could still use the loop, but I can work around them. (I would like to use this with more complicated code)

推荐答案

而不是尝试检测您是否位于最后一项,而是在打印下一个时打印逗号和换行符(仅要求检测您是否是第一个):

Rather than try and detect if you are at the last item, print the comma and newline when printing the next (which only requires detecting if you are at the first):

a = ['hello', 9, 3.14, 9]
for i, item in enumerate(a):
    if i:  # print a separator if this isn't the first element
        print(',')
    print(item, end='')
print()  # last newline

enumerate()函数为每个元素添加一个计数器(请参阅枚举是什么意思?),并且除0(第一个元素)外,if i:对于计数器的所有值都为true.

The enumerate() function adds a counter to each element (see What does enumerate mean?), and if i: is true for all values of the counter except 0 (the first element).

或使用print()插入分隔符:

print(*a, sep=',\n')

sep值插入每个参数之间(*aa中的所有值作为单独的参数应用,请参见

The sep value is inserted between each argument (*a applies all values in a as separate arguments, see What does ** (double star) and * (star) do for parameters?). This is more efficient than using print(',n'.join(map(str, a))) as this doesn't need to build a whole new string object first.

这篇关于检测项目是否为列表中的最后一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆