파이썬에서 for 루프의 첫 번째 항목을 건너 뛰시겠습니까?
파이썬에서는 다음과 같은 것을 어떻게합니까?
for car in cars:
# Skip first and last, do work for rest
다른 답변은 시퀀스에서만 작동합니다.
반복 가능한 경우 첫 번째 항목을 건너 뛰십시오.
itercars = iter(cars)
next(itercars)
for car in itercars:
# do work
마지막을 건너 뛰려면 다음을 수행하십시오.
itercars = iter(cars)
# add 'next(itercars)' here if you also want to skip the first
prev = next(itercars)
for car in itercars:
# do work on 'prev' not 'car'
# at end of loop:
prev = car
# now you can do whatever you want to do to the last one on 'prev'
파이썬에서 첫 번째 요소를 건너 뛰려면 간단히 쓸 수 있습니다.
for car in cars[1:]:
# Do What Ever you want
또는 마지막 요소를 건너 뛰려면
for car in cars[:-1]:
# Do What Ever you want
이 개념을 모든 시퀀스에 사용할 수 있습니다.
다음은 iterable의 시작과 끝에서 여러 항목을 건너 뛰는보다 일반적인 생성기 함수입니다.
def skip(iterable, at_start=0, at_end=0):
it = iter(iterable)
for x in itertools.islice(it, at_start):
pass
queue = collections.deque(itertools.islice(it, at_end))
for x in it:
queue.append(x)
yield queue.popleft()
사용법 예 :
>>> list(skip(range(10), at_start=2, at_end=2))
[2, 3, 4, 5, 6, 7]
첫 번째 항목을 건너 뛰는 가장 좋은 방법은 다음과 같습니다.
from itertools import islice
for car in islice(cars, 1, None):
# do something
이 경우 islice는 반복기의 끝을 나타내는 시작점 1과 끝점 없음으로 호출됩니다.
iterable의 끝에서 항목을 건너 뛸 수 있으려면 길이를 알아야합니다 (항상 목록에 대해서는 가능하지만 반복 할 수있는 모든 것은 아님). 예를 들어 islice (cars, 1, len (cars) -1)는 자동차 목록의 첫 번째 항목과 마지막 항목을 건너 뜁니다.
for item in do_not_use_list_as_a_name[1:-1]:
#...do whatever
@SvenMarnach의 답변을 기반으로하지만 조금 더 간단하고 deque를 사용하지 않습니다.
>>> def skip(iterable, at_start=0, at_end=0):
it = iter(iterable)
it = itertools.islice(it, at_start, None)
it, it1 = itertools.tee(it)
it1 = itertools.islice(it1, at_end, None)
return (next(it) for _ in it1)
>>> list(skip(range(10), at_start=2, at_end=2))
[2, 3, 4, 5, 6, 7]
>>> list(skip(range(10), at_start=2, at_end=5))
[2, 3, 4]
또한 내 timeit
결과에 따르면 이것은 deque 솔루션보다 약간 빠릅니다.
>>> iterable=xrange(1000)
>>> stmt1="""
def skip(iterable, at_start=0, at_end=0):
it = iter(iterable)
it = itertools.islice(it, at_start, None)
it, it1 = itertools.tee(it)
it1 = itertools.islice(it1, at_end, None)
return (next(it) for _ in it1)
list(skip(iterable,2,2))
"""
>>> stmt2="""
def skip(iterable, at_start=0, at_end=0):
it = iter(iterable)
for x in itertools.islice(it, at_start):
pass
queue = collections.deque(itertools.islice(it, at_end))
for x in it:
queue.append(x)
yield queue.popleft()
list(skip(iterable,2,2))
"""
>>> timeit.timeit(stmt = stmt1, setup='from __main__ import iterable, skip, itertools', number = 10000)
2.0313770640908047
>>> timeit.timeit(stmt = stmt2, setup='from __main__ import iterable, skip, itertools, collections', number = 10000)
2.9903135454296716
글쎄, 구문은 실제로 파이썬이 아닙니다.
Iterations in Python are over he contents of containers (well, technically it's over iterators), with a syntax for item in container
. In this case, the container is the cars
list, but you want to skip the first and last elements, so that means cars[1:-1]
(python lists are zero-based, negative numbers count from the end, and :
is slicing syntax.
So you want
for c in cars[1:-1]:
do something with c
An alternative method:
for idx, car in enumerate(cars):
# Skip first line.
if not idx:
continue
# Skip last line.
if idx + 1 == len(cars):
continue
# Real code here.
print car
If cars
is a sequence you can just do
for car in cars[1:-1]:
pass
The more_itertools
project extends itertools.islice
to handle negative indices.
Example
import more_itertools as mit
iterable = 'ABCDEFGH'
list(mit.islice_extended(iterable, 1, -1))
# Out: ['B', 'C', 'D', 'E', 'F', 'G']
Therefore, you can elegantly apply it slice elements between the first and last items of an iterable:
for car in mit.islice_extended(cars, 1, -1):
# do something
I do it like this, even though it looks like a hack it works every time:
ls_of_things = ['apple', 'car', 'truck', 'bike', 'banana']
first = 0
last = len(ls_of_things)
for items in ls_of_things:
if first == 0
first = first + 1
pass
elif first == last - 1:
break
else:
do_stuff
first = first + 1
pass
Here's my preferred choice. It doesn't require adding on much to the loop, and uses nothing but built in tools.
Go from:
for item in my_items:
do_something(item)
to:
for i, item in enumerate(my_items):
if i == 0:
continue
do_something(item)
참고URL : https://stackoverflow.com/questions/10079216/skip-first-entry-in-for-loop-in-python
'Programming' 카테고리의 다른 글
팬더 데이터 프레임의 열 정규화 (0) | 2020.06.08 |
---|---|
잔가지 템플릿으로 현재 URL을 얻으시겠습니까? (0) | 2020.06.08 |
JavaScript에서 여러 CSS 스타일을 설정하려면 어떻게해야합니까? (0) | 2020.06.08 |
자동 레이아웃을 사용하여 텍스트로 확장되는 UITextView (0) | 2020.06.08 |
PHP는 나이를 계산 (0) | 2020.06.08 |