문제 설명
for 루프를 중단하지 않고 if 문을 중지하고 다른 if에 영향을 줍니다. (Stop if statement without breaking for loop and affect other ifs)
파이썬을 사용하여 일부 .csv 파일을 처리하고 있습니다. .csv 파일에는 많은 행이 있습니다. 동일한 행이 여러 개 있습니다. 이 파일을 연 후 for row in reader:
루프에서 첫 번째 반복 행을 찾아 변수에 할당하고 싶습니다. 그런 다음 루프의 다른 행을 계속 처리합니다.
문제는 루프가 다른 동일한 행을 만날 때 루프를 끊지 않고 if 문이 다시 실행된다는 것입니다. 원하는 첫 번째 행을 찾았을 때 if 문이 한 번만 실행되기를 원합니다. 한 번이면 충분하지만 if 문을 여러 번 실행하면 중복성이 발생합니다.
if 조건이 처음 충족될 때만 이 if 문을 실행하는 방법은 무엇입니까? 원하는 첫 번째 행이 발견되면 루프를 끊고 for row in reader:
를 반복할 수 있습니다. 다른 행을 처리하려면 단일 루프에서 이를 수행하는 방법이 있어야 한다고 생각합니다.
참조 솔루션
방법 1:
This a common pattern in in programming. Set a flag once you've fulfilled the condition for the first time. then ignore that condition if your flag is already set.
already_set = False
row_variable = None
for row in reader:
if (row meets some condition) and (not already_set):
row_variable = row
already_Set = True
# now row_variable holds the first row that met your condition
# or it holds None if no rows meet the condition
방법 2:
You can just use a boolean value to represent whether you've already processed a matching row or not, and an additional check in your if
statement.
found = False
for r in rows:
if ( r == "whatever conidition for the row" and not found):
found = True
# processing code
(by Wanlie、turbulencetoo、xgord)