여기에서하는 일은 for 루프를 정의하는 실제 방법이 아닙니다. 당신이 사용하는 것은 목록 이해력입니다.
목록 인식이란 무엇입니까?
목록 이해는 루프 값을 신속하게 동일시하는 데 사용됩니다. 예를 들어 :의 값을 줄 것이다
x = [i for i in range(10) if i % 2 == 0]
모두 :
x = []
for i in range(10):
if i % 2 == 0:
x.append(i)
은 동일합니다
>>> x
[0, 2, 4, 6, 8]
좋아 ... 그럼 어떻게 for 루프가 정의된다?
for 루프는 명령문의 시작 부분에 for
키워드를 사용하여 정의되며 명령문의 연속이 아닙니다. , 당신은 당신이 같은 들여 쓰기 수준 유지하여 check_image_size(os.path.join(folder, name))
후 더 라인을 추가 할 수 있습니다 것을 볼 것입니다 이제
# ...
names = []
for name in os.listdir(folder):
if not name.endswith('bin.png') if not name.endswith('.jpg') if not name.endswith('.nrm.png'):
names.append(check_image_size(os.path.join(folder, name)))
: 위에서 볼 수 있듯이, 코드는 같은으로 변환 할 수
# ...
names = []
for name in os.listdir(folder):
if not name.endswith('bin.png') if not name.endswith('.jpg') if not name.endswith('.nrm.png'):
names.append(check_image_size(os.path.join(folder, name)))
# Add more things here
my_other_function_to_run(x)
more_other_functions(y)
내 코드가 여전히 실행되지 않습니다!
if
문에 if
을 두 개 이상 가질 수 없기 때문입니다. 대신 정확하게을 사용하여 엄격한 관계를 나타냅니다. 물론
# ...
names = []
for name in os.listdir(folder):
if not name.endswith('bin.png') and not name.endswith('.jpg') and not name.endswith('.nrm.png'):
names.append(check_image_size(os.path.join(folder, name)))
# Add more things here
my_other_function_to_run(x)
more_other_functions(y)
는, 당신은 if
문을 중첩 할 수 있지만, 그들은 매우 좋은하지 않습니다 : 제가 위에서 말했듯이
# ...
names = []
for name in os.listdir(folder):
if not name.endswith('bin.png')
if not name.endswith('.jpg')
if not name.endswith('.nrm.png'):
names.append(check_image_size(os.path.join(folder, name)))
# Add more things here
my_other_function_to_run(x)
more_other_functions(y)
마지막 주
, 당신은 더 이상하지 말았어야 if
문의 if
키워드 이것은 목록 이해를 위해서도 마찬가지로 적용됩니다. 그러므로 원래의 코드는 :
# ...
names = [check_image_size(os.path.join(folder, name))
for name in os.listdir(folder)
if not name.endswith('bin.png')
and not name.endswith('.jpg')
and not name.endswith('.nrm.png')
]
등으로 좋았을 것입니다. 그러나 for 루프 내부에서 여러 함수를 호출하는 것에 대한 아이디어는 없습니다. 귀하의 답변에 감사드립니다. –
@AnayBose 최근 편집을 참조하십시오. –