我想对列表中的第一项做一些不同的事情
for item in list:
# only if its the first item, do something
# otherwise do something else
Run Code Online (Sandbox Code Playgroud)
一些选择,按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)
您可以使用 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)
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优于此。你也许应该用它来代替。
| 归档时间: |
|
| 查看次数: |
1143 次 |
| 最近记录: |