简体   繁体   English

如何只对python循环中的第一项执行某些操作?

[英]How to do something only to the first item within a loop in python?

I want to do something different to the the first item in a list.我想做一些与列表中的第一项不同的事情。 What is the most pythonic way of doing so?这样做的最pythonic方式是什么?

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

    # otherwise do something else

A few choices, in descending order of Pythonicity:一些选择,按 Pythonicity 的降序排列:

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

Or:或者:

first = True
for item in lst:
    if first:
        first = False
        # first item 
    else:
        # other items 

Or:或者:

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

You can create an iterator over the list using iter(), then call next() on it to get the first value, then loop on the remainder.您可以使用 iter() 在列表上创建一个迭代器,然后对其调用 next() 以获取第一个值,然后在其余部分上循环。 I find this a quite elegent way to handle files where the first line is the header and the rest is data, ie我发现这是处理文件的一种非常优雅的方式,其中第一行是标题,其余的是数据,即

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)
do_something_with_first_item(lst[0])
for item in lst[1:]:
    do_something_else(item)

Or:或者:

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)

Do not use list as a variable name, because this shadows the built-in function list() .不要使用list作为变量名,因为这会影响内置函数list()

The enumerate -based solution in jonrsharpe's answer is superior to this. jonrsharpe 的答案中基于enumerate的解决方案优于此。 You should probably use that instead.您可能应该改用它。

Use a flag that you change after processing the first item.使用在处理第一个项目后更改的标志。 For example:例如:

first = True
for item in my_list:
    if first:
        # Processing unique to the first item
        first = False
    else:
        # Processing unique to other items
    # Shared processing

You could also just process the first item:您也可以只处理第一项:

first = my_list.pop(0)
# Process first
for item in my_list:
    # Process item

# Add the first item back to the list at the beginning
my_list.insert(0, first)

jonrsharpe's first version using enumerate is clean and simple, and works with all iterables: jonrsharpe 使用enumerate的第一个版本简洁明了,适用于所有可迭代对象:

for index, item in enumerate(lst):
    if not index:
        do_something_with_first_item(item)
    else:
        do_something_else(item)

senshin's first solution using lst[0] and lst[1:] is even simpler, but only works with sequences: senshin 使用lst[0]lst[1:]的第一个解决方案更简单,但仅适用于序列:

do_something_with_first_item(lst[0])
for item in lst[1:]:
    do_something_else(item)

You can get the best of both worlds by using iterators directly:您可以通过直接使用迭代器来两全其美:

it = iter(lst)
do_something_with_first_item(next(it))
for item in it:
    do_something_else(item)

But, despite being the best of both worlds, it's actually not quite as simple as either.但是,尽管它是两全其美的,但实际上并不像两者一样简单。 This is only clearly worth doing if you know you have an iterator (so you can skip the first line), or you need one anyway to do itertools and genexpr and similar stuff to (so you were already going to write the first line).如果你知道你有一个迭代器(所以你可以跳过第一行),或者你无论如何都需要一个迭代器来做itertools和 genexpr 以及类似的东西(所以你已经准备写第一行),这显然是值得做的。 Whether it's worth doing in other cases is more of a style issue.在其他情况下是否值得这样做更多的是风格问题。

I want to do something different to the the first item in a list.我想做一些与列表中第一项不同的事情。 What is the most pythonic way of doing so?最Python化的方式是什么?

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

    # otherwise do something else

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 Python 3 的 for 循环中获取一项并专门做某事? - How to get one item and do something specifically in a for loop in Python 3? python for 循环仅返回第一个索引项 - python for loop is only returning first index item Selenium Python for 循环只获取第一项 - Selenium Python for loop only gets first item 如何遍历文本文件但在第一行做一些不同的事情,Python - How can I loop through a textfile but do something different on the first line, Python 如何制作仅在for循环中出现的elif命令才能为列表中某项的某些实例注册? - How do I make an elif command which occurs in a for loop only register for certain instances of an item within the list? 如何在循环内(但仅在第一次迭代之后)更改条件? - How do I change a condition within a loop, but only after the first iteration? 如何在 for 循环中选择“for”循环的第一个值? - how do i select the first value of "for" loop within the for loop? 如何在python scrapy中删除数组中项目的第一个字符 - how to remove first characters of an item within array in python scrapy 你如何让某物在 python 中循环特定次数? - how do you make something loop a specific amount of times in python? Xpath for 循环只给出第一个结果。 我如何获得所有这些? (Python,Scrapy) - Xpath for loop gives only first result. How do I get all of them? (Python, Scrapy)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM