파이썬 목록 이해를 들여 쓰기하는 방법?
목록 이해는 특정 상황에서 유용 할 수 있지만 읽기가 다소 끔찍할 수도 있습니다. 약간 과장된 예로서 다음을 어떻게 들여 쓰시겠습니까?
allUuids = [x.id for x in self.db.query(schema.allPostsUuid).execute(timeout = 20) if x.type == "post" and x.deleted is not False]
얼마나 오래 있는지에 따라 다릅니다. 나는 다음과 같이 구조화하는 경향이 있습니다.
[x.id for x
in self.db.query(schema.allPostsUuid).execute(timeout=20)
if x.type == 'post'
and x.deleted is not False
and ...
and ...]
이렇게하면 모든 표현에 고유 한 라인이 있습니다.
선이 너무 커지면 람다 또는 표현식으로 추출하고 싶습니다.
transform = lambda x: x.id
results = self.db.query(schema.allPostsUuid).execute(timeout=20)
condition = lambda x: x.deleted is not False and ... and ...
[transform(x) for x in results if condition(x)]
그리고 람다가 너무 길어지면 함수로 승격됩니다.
내가 일하는 곳에서 우리의 코딩 가이드 라인은 다음과 같이해야합니다.
all_posts_uuid_query = self.db.query(schema.allPostsUuid)
all_posts_uuid_list = all_posts_uuid_query.execute(timeout=20)
all_uuid_list = [
x.id
for x in all_posts_uuid_list
if (
x.type == "post"
and
not x.deleted # <-- if you don't care about NULLs / None
)
]
allUuids = [x.id
for x in self.db.query(schema.allPostsUuid).execute(timeout = 20)
if x.type == "post" and x.deleted is not False]
저에게는 너무 많습니다. "type"과 "deleted"가 분명히 db 쿼리의 일부이기 때문에 끔찍한 예일 수도 있습니다.
나는 목록 이해력이 여러 줄에 걸쳐 있으면 아마도 목록 이해력이 될 수 없다고 생각하는 경향이 있습니다. 그렇게 말하면서 나는 보통 다른 사람들이 가지고있는 것처럼 "if"로 나누고 여기서 대답 할 것입니다.
당신은 그것을 위해 목록 이해력을 사용해서는 안됩니다 .
목록 이해는 멋진 기능이지만 일반 코드가 아니라 바로 가기를 의미합니다.
이러한 긴 스 니펫의 경우 일반 블록을 사용해야합니다.
allUuids = []
for x in self.db.query(schema.allPostsUuid).execute(timeout = 20) :
if x.type == "post" and x.deleted is not False :
allUuids.append(x.id)
똑같은 동작으로 훨씬 더 읽기 쉽습니다. 귀도는 당신을 자랑스럽게 생각합니다 :-)
당신이 이해력을 가지고 있다면 orestis의 대답 은 좋습니다.
더 복잡한 이해를 위해서는 다음과 함께 생성기를 사용하는 것이 좋습니다 yield
.
allUuids = list(self.get_all_uuids())
def get_all_uuids(self):
for x in self.db.query(schema.allPostsUuid).execute(timeout = 20):
if x.type == "post" and x.deleted is not False:
yield x.id
어때 :
allUuids = [x.id for x in self.db.query(schema.allPostsUuid).execute(timeout = 20)
if (x.type == "post" and x.deleted is not False)]
Generally, long lines can be avoided by pre-computing subexpressions into variables, which might add a minuscule performance cost:
query_ids = self.db.query(schema.allPostsUuid).execute(timeout = 20)
allUuids = [x.id for x in query_ids
if (x.type == "post" and x.deleted is not False)]
By the way, isn't 'is not False
' kind-of superfluous ? Are you worried about differentiating between None and False ? Because otherwise, it suffices to leave the condition as only: if (x.type == "post" and x.deleted)
참고URL : https://stackoverflow.com/questions/311588/how-to-indent-python-list-comprehensions
'IT TIP' 카테고리의 다른 글
ActiveMQ 대 Apollo 대 Kafka (0) | 2020.11.23 |
---|---|
SQL 케이스 표현식 구문? (0) | 2020.11.23 |
현재 파일을 덮어 쓰도록 SVN 체크 아웃 명령 강제 실행 (0) | 2020.11.23 |
MS Excel 데이터를 SQL Server에 붙여 넣기 (0) | 2020.11.23 |
JSON을 사용한 Spring MVC 멀티 파트 요청 (0) | 2020.11.22 |