当它是列表中的第一项时,大多数pythonic方式做某事

Dap*_*Dap 1 python loops list

我想对列表中的第一项做一些不同的事情

for item in list:
    # only if its the first item, do something

    # otherwise do something else
Run Code Online (Sandbox Code Playgroud)

jon*_*rpe 7

一些选择,按Pythonicity的降序排列:

for index, item in enumerate(lst): # note: don't use list
    if not index: # or if index == 0:
        # first item
    else:
        # other items
Run Code Online (Sandbox Code Playgroud)

要么:

first = True
for item in lst:
    if first:
        first = False
        # first item 
    else:
        # other items 
Run Code Online (Sandbox Code Playgroud)

要么:

for index in range(len(lst)):
    item = lst[i]
    if not index:
        # first item
    else:
        # other items
Run Code Online (Sandbox Code Playgroud)

  • 与其他几个选项相比,使用“枚举”的一个优点是,被迭代的对象是否支持索引都无关紧要。 (3认同)
  • @adsmith:PEP 8说不然.在stdlib中有一些确切的`if not index:`的例子. (3认同)
  • 我喜欢枚举,但是不知道是否要使用`if not index`。如果if index == 0更明确。 (2认同)

Dav*_*rth 7

您可以使用 iter() 在列表上创建一个迭代器,然后对其调用 next() 以获取第一个值,然后在其余部分上循环。我发现这是处理文件的一种非常优雅的方式,其中第一行是标题,其余的是数据,即

list_iterator = iter(lst)

# consume the first item
first_item = next(list_iterator)

# now loop on the tail
for item in list_iterator:
    print(item)
Run Code Online (Sandbox Code Playgroud)


sen*_*hin 6

do_something_with_first_item(lst[0])
for item in lst[1:]:
    do_something_else(item)
Run Code Online (Sandbox Code Playgroud)

或者:

is_first_item = True
for item in lst:
    if is_first_item:
        do_something_with_first_item(item)
        is_first_item = False
    else:
        do_something_else(item)
Run Code Online (Sandbox Code Playgroud)

不要用作list变量名,因为这会隐藏内置函数list()

jonrsharpe 的答案中基于 - 的解决方案enumerate优于此。你也许应该用它来代替。