본문으로 바로가기

one line list using for, if ,in

category Studies/Python 2022. 3. 2. 21:35

코드의 가독성을 높이면서 좀 더 간단하게 for 과 if 문을 사용하여 리스트를 만드는 방법을 알아냈다.

 

다음은 bs4 에서 이미지를 웹스크래핑 해오는 코드이다.

for ele in cols:
     img = ele.find("img",attrs={'class':'img-circle'})
     if not not img:
         imgsrc =img['src']

table의 columns 에서 img 태그가 있으면 imgsrc 변수를 지정하는 코드이다.

 

무려 4줄이나 사용해야하지만, 다음처럼 쓰면 1줄로 코드를 쓸 수 있다.

imgsrc = [ ele.find("img",attrs={'class':'img-circle'}) for ele in cols if not not ele.find("img",attrs={'class':'img-circle'})]

가로로 훨씬 더 길어보이긴 하지만 , 4줄을 1줄로 줄인다는 점에서 나는 이 방법이 좋았다.

 

| 참조

https://stackoverflow.com/questions/17321138/one-line-list-comprehension-if-else-variants