Python에서 여러 줄의 dict를 포맷하는 적절한 방법은 무엇입니까?
Python에서는 코드에 여러 줄의 dict를 쓰고 싶습니다.포맷에는 몇 가지 방법이 있습니다.다음은 제가 생각할 수 있는 몇 가지 사항입니다.
mydict = { "key1": 1, "key2": 2, "key3": 3, }
mydict = { "key1": 1, "key2": 2, "key3": 3, }
mydict = { "key1": 1, "key2": 2, "key3": 3, }
위의 내용 중 어느 것이든 구문적으로는 맞다는 것을 알지만, Python dits에 대해 선호하는 들여쓰기 및 줄 바꿈 스타일이 하나 있다고 생각합니다.그것은 무엇일까요?
주의: 이것은 구문의 문제가 아닙니다.위의 모든 것은 (내가 아는 한) 유효한 Python 문장으로 서로 동등합니다.
저는 3번을 써요.긴 목록, 튜플 등에 대해서도 동일합니다.움푹 들어간 곳보다 더 많은 공간을 추가할 필요가 없습니다.항상 그렇듯이, 일관성을 유지하라.
mydict = {
"key1": 1,
"key2": 2,
"key3": 3,
}
mylist = [
(1, 'hello'),
(2, 'world'),
]
nested = {
a: [
(1, 'a'),
(2, 'b'),
],
b: [
(3, 'c'),
(4, 'd'),
],
}
마찬가지로, 공백 없이 큰 문자열을 포함하는 방법을 선호합니다(예를 들어, 세 개의 따옴표로 묶은 여러 줄 문자열을 사용하는 경우).
data = (
"iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABG"
"l0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAEN"
"xBRpFYmctaKCfwrBSCrRLuL3iEW6+EEUG8XvIVjYWNgJdhFjIX"
"rz6pKtPB5e5rmq7tmxk+hqO34e1or0yXTGrj9sXGs1Ib73efh1"
"AAAABJRU5ErkJggg=="
)
우선 스티븐 럼발스키의 말처럼 "PEP8은 이 문제를 다루지 않는다"는 것은 개인적인 선호의 문제이다.
저는 당신의 포맷 3과 비슷하지만 동일하지 않은 포맷을 사용합니다.여기 내 것이 있고, 왜 그런가.
my_dictionary = { # Don't think dict(...) notation has more readability
"key1": 1, # Indent by one press of TAB (i.e. 4 spaces)
"key2": 2, # Same indentation scale as above
"key3": 3, # Keep this final comma, so that future addition won't show up as 2-lines change in code diff
} # My favorite: SAME indentation AS ABOVE, to emphasize this bracket is still part of the above code block!
the_next_line_of_code() # Otherwise the previous line would look like the begin of this part of code
bad_example = {
"foo": "bar", # Don't do this. Unnecessary indentation wastes screen space
"hello": "world" # Don't do this. Omitting the comma is not good.
} # You see? This line visually "joins" the next line when in a glance
the_next_line_of_code()
btw_this_is_a_function_with_long_name_or_with_lots_of_parameters(
foo='hello world', # So I put one parameter per line
bar=123, # And yeah, this extra comma here is harmless too;
# I bet not many people knew/tried this.
# Oh did I just show you how to write
# multiple-line inline comment here?
# Basically, same indentation forms a natural paragraph.
) # Indentation here. Same idea as the long dict case.
the_next_line_of_code()
# By the way, now you see how I prefer inline comment to document the very line.
# I think this inline style is more compact.
# Otherwise you will need extra blank line to split the comment and its code from others.
some_normal_code()
# hi this function is blah blah
some_code_need_extra_explanation()
some_normal_code()
키는 문자열이기 때문에 가독성에 대해 이야기하고 있기 때문에, 다음과 같이 하는 것이 좋습니다.
mydict = dict(
key1 = 1,
key2 = 2,
key3 = 3
)
보통 큰 비단뱀 오브젝트가 있으면 포맷하기가 상당히 어렵습니다.저는 개인적으로 그것을 위해 몇 가지 도구를 사용하는 것을 선호합니다.
다음은 Python-Beautifier - www.cleancss.com/python-beautify 입니다. 데이터를 즉시 맞춤형 스타일로 바꿀 수 있습니다.
flake8 - python 코드에서 스타일 일관성을 적용하는 유틸리티로 코드 구문을 체크하고 이를 개선하기 위한 지침을 제공합니다(https://www.flake8rules.com/rules/E133.html) 참조).
mydict = {
"key1": 1,
"key2": 2,
"key3": 3,
}
튜토리얼이나 그 외의 것에 대해서는, 항상 2번이 마음에 드는 것 같습니다만, 그 중에서도 개인 취향입니다.
dict(rank = int(lst[0]),
grade = str(lst[1]),
channel=str(lst[2])),
videos = float(lst[3].replace(",", " ")),
subscribers = float(lst[4].replace(",", "")),
views = float(lst[5].replace(",", "")))
일반적으로 마지막 엔트리에 콤마를 포함하지 않지만 Python이 이를 수정합니다.
언급URL : https://stackoverflow.com/questions/6388187/what-is-the-proper-way-to-format-a-multi-line-dict-in-python
'programing' 카테고리의 다른 글
Python을 사용하여 문자열의 각 문자 반복 (0) | 2022.09.09 |
---|---|
Vuex: [Vue warn] :계산된 속성 "사용자 이름"이 할당되었지만 설정자가 없습니다. (0) | 2022.09.09 |
여기 뭐가 문제인지 알 수가 없어요 (0) | 2022.09.09 |
MariaDB - 주문이 있는 그룹화 기준 (0) | 2022.09.08 |
D_XOPEN_SOURCE는 무엇을 의미합니까? (0) | 2022.08.25 |