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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39808908/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 22:44:25  来源:igfitidea点击:

Detect If Item is the Last in a List

pythonlistpython-3.x

提问by nedla2004

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:

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

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

And I would like this output:

我想要这个输出:

hello,
9,
3.14,
9

But I get this output:

但我得到这个输出:

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)

我明白为什么我会得到我不想要的输出。如果我仍然可以使用循环,我更愿意,但我可以解决它们。(我想在更复杂的代码中使用它)

回答by Matt M.

While these answers may work for the specific case of the OP, I found they were unsatisfactory for broader application.

虽然这些答案可能适用于 OP 的特定情况,但我发现它们对于更广泛的应用并不令人满意。

Here are the methods I could think of/saw here and their respective timings.

以下是我在这里能想到/看到的方法以及它们各自的时间。

Index Method

索引法

urlist_len = len(urlist)-1
for x in urlist:
    if urlist.index(x) == urlist_len:
        pass

Negative Slice Method

负切片法

for x in urlist:
    if x == urlist[-1]:
        pass

Enumerate Method

枚举方法

urlist_len = len(urlist)-1
for index, x in enumerate(urlist):
    if index == urlist_len:
        pass

Here are some timing for some different methods:

以下是一些不同方法的一些时间:

╔════════════════════════════════════════════════════════════════╗
║                       Timing Results (s)                       ║
╠═══════════════════════╦════╦═════════╦════════╦═══════╦════════╣
║ List size             ║ 20 ║ 200     ║ 2000   ║ 20000 ║ 200000 ║
╠═══════════════════════╬════╬═════════╬════════╬═══════╬════════╣
║                       ║ 0  ║ 0.0006  ║ 0.051  ║ 5.2   ║ 560    ║
║ Index Method          ║    ║         ║        ║       ║        ║
╠═══════════════════════╬════╬═════════╬════════╬═══════╬════════╣
║                       ║ 0  ║ 0       ║ 0.0002 ║ 0.003 ║ 0.034  ║
║ Negative Slice Method ║    ║         ║        ║       ║        ║
╠═══════════════════════╬════╬═════════╬════════╬═══════╬════════╣
║ Enumerate Method      ║ 0  ║ 0.00004 ║ 0.0005 ║ 0.016 ║ 0.137  ║
╚═══════════════════════╩════╩═════════╩════════╩═══════╩════════╝

Note: values <10us rounded to 0

注意:值 <10us 舍入为 0

As you can see, the index method is alwaysslower, and it only get exponentially worse as the list size increases. I don't see any reason to use it ever. The Negative slice method is the fastest in all cases, but if you have duplicate items in your list, it will give you a false positive. Also, the negative slice method requires that the sequence you are iterating over supports indexing. So, in the case of duplicate items in your list (or not index supporting sequence) use the fast-but-not-fastest enumerate method.

如您所见,索引方法总是较慢,而且随着列表大小的增加,它只会呈指数级恶化。我看不出有任何理由使用它。Negative slice 方法在所有情况下都是最快的,但是如果您的列表中有重复的项目,它会给您一个误报。此外,负切片方法要求您迭代的序列支持索引。因此,如果列表中有重复项(或不支持索引的序列),请使用快速但不是最快的枚举方法。

Edit: as a commentator noted, calculating the length of the list within the loop isn't ideal. I was able to shave 35% off the enumerate method (not reflected in the table at this moment) using this knowledge.

编辑:正如评论员所指出的,计算循环内列表的长度并不理想。使用这些知识,我能够将 enumerate 方法(目前未反映在表中)削减 35%。



tldr: use negative slice if all elements are unique and sequence supports indexing, otherwise enumerate method

tldr:如果所有元素都是唯一的并且序列支持索引,则使用负切片,否则使用 enumerate 方法

回答by Martijn Pieters

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

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).

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

Or use print()to insert separators:

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

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

The sepvalue is inserted between each argument (*aapplies all values in aas 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.

sep值插入在每个参数之间(*a将所有值应用a为单独的参数,请参阅**(双星)和 *(星)对参数有何作用?)。这比使用更有效,print(',n'.join(map(str, a)))因为这不需要先构建一个全新的字符串对象。

回答by skovorodkin

If you really just want to join your elements into a comma+newline-separated string then it's easier to use str.joinmethod:

如果您真的只想将元素加入逗号+换行符分隔的字符串,那么使用str.join方法会更容易:

elements = ['hello', 9, 3.14, 9]
s = ',\n'.join(str(el) for el in elements)
# And you can do whatever you want with `s` string:
print(s)

回答by Shivek Khurana

You are not getting the expected output because in your code you say, "Hey python, print a comma if current element is not equal to last element."

您没有得到预期的输出,因为在您的代码中您说:“嘿,python,如果当前元素不等于最后一个元素,则打印一个逗号。”

Second element 9 is equal to last element, hence the comma is not printed.

第二个元素 9 等于最后一个元素,因此不打印逗号。

The right way to check for the last element is to check the index of element :

检查最后一个元素的正确方法是检查 element 的索引:

a = ['hello', 9, 3.14, 9]
for item in a:
    print(item, end='')
    if a.index(item) != len(a)-1: #<--------- Checking for last element here
        print(', ')

(Also, this might throw a value error. You should check for that too.)

(此外,这可能会引发值错误。您也应该检查一下。)

回答by Malzyhar

If you are just looking to see if the item is last in the (or any item in any list) you could try using a function to check if an item is last in a list.

如果您只是想查看该项目是否在(或任何列表中的任何项目)中的最后一个,您可以尝试使用一个函数来检查一个项目是否在列表中的最后一个。

a = ['hello', 9, 3.14, 9]
def is_last(alist,choice):
        if choice == alist[-1]:
            print("Item is last in list!")
            return True
        else:
            print("Item is not last")
            return False

if is_last(a,9) == True:
    <do things>

else:
    <do other things>

回答by Smilez

Test if the index value is the length of the list - 1

测试索引值是否为列表的长度 - 1

Like this:

像这样:

    if item != (len(a) - 1):
        #whatever you wanted to do

    #or, if you want the index to be the last...
    if item == (len(a) - 1):
        #whatever you wanted to do