Еще несколько вещей, о которых я думал. Поскольку мой последний пост получил некоторое внимание, я подумал, что я пишу немного больше о вещах, которые я пришел, Accross в Python. Изначально из Java, большинство из этих вещей пришли для меня удивлением.
Оператор Тильде
# You can index lists from the front a = ['a', 'b', 'c', 'd', 'e'] print(a[0]) # 'a' print(a[1]) # 'b' # You can also index them from the back # starting with -1 and going backwards print(a[-1]) # 'e' print(a[-2]) # 'd' # The tilde operator when applied to a number `x` calculates `-x - 1`, # which can be useful for list indexing # # x ~x # 0 -1 # 1 -2 # 2 -3 # 3 -4 # 4 -5 print(a[~0]) # 'e' = 0th element from the back print(a[~1]) # 'd' = 1st from the back
Так ссылка
[0] и 0
# Consider this function def foo(data): """Prints the status of my list.""" if data: # Don't do this print("The list contains some items.") else: print("We got an empty list.") foo([]) # ok -> "We got an empty list." foo([1,2,3,4]) # ok -> "The list contains some items." # Empty lists are treated as false in Python. # However, False and 0 are also false, which can lead to some # unexpected behavior if your client, does not know that you # expect him to pass a list. foo([0]) # still ok -> "The list contains some items." foo(0) # NOT ok -> "We got an empty list." foo(False) # NOT ok -> "We got an empty list." def foo(data): if len(data) > 0: # Safer version print("The list contains some items.") else: print("We got an empty list.")
Значения по умолчанию
Значения по умолчанию в Python не должны быть измельчены, такие как список или словарь. Значения по умолчанию оцениваются, когда def
Заявление, которое они принадлежат, выполнен. То есть они оцениваются только один раз.
# Don't do this def foo(bar=[]): bar.append(1) return bar foo() # returns [1] --> ok foo() # returns [1,1] --> not ok = the same list as before foo() # returns [1,1,1] --> also not ok = again, the same list # Do this instead def foo(bar=None): if bar is None: bar=[] ...
Много способов назвать ту же функцию
def draw_line(length, type="solid", color="black"): print(length, type, color) draw_line(5) # 1) 5 solid black draw_line(length=5) # 2) 5 solid black draw_line(5, "dashed") # 3) 5 dashed black draw_line(5, "dashed", "green") # 4) 5 dashed green draw_line(5, type="dashed", color="green") # 5) 5 dashed green # Can we take this a step further? Definitely. draw_line(type="dashed", length=5) # 6) 5 dashed black args = [5] # could also be a tuple (5,) draw_line(*args) # 7) 5 solid black args = {"length": 5, "color": green} draw_line(**args) # 8) 5 solid green
Некоторое объяснение
Подробнее о функциях
# Pre-fill functions with the arguments you use often def draw_line(length, type="solid", color="black"): print(length, type, color) from functools import partial draw_green_line = partial(draw_line, color="green") draw_green_line(5) # 5 solid green draw_unit_line = partial(draw_line, length=1) draw_unit_line() # 1 solid black # If you want to use keyword arguments but you do not want # to provide default values, you can do that as well def draw_line(*, length, type, color): # all three are required ... # Allow some positional arguments, but forbid 3) and 4) def draw_line(length, *, type="solid", color="black"): # only length is required ...
Любые еще идеи о том, как вызывать функцию? Знайте какие-либо другие кодирование Pythonic, что вы нашли полезными в прошлом? Комментарий ниже.
Соответствующая загадка ссылки
Оригинал: “https://dev.to/r0f1/4-useful-things-in-python”