Просто некоторые ловушки и подводные камни, которые потребовались мне некоторое время, чтобы привыкнуть в Python.
Список методов против встроенных методов
# sort(), sorted(), reverse(), reversed() # sort() modifies the existing list and is a function of the list object # sorted() returns a new list and is a built-in function a = [5,2,8,1,9,3] sorted(a) # ok -> [1, 2, 3, 5, 8, 9] a.sort() # ok -> [1, 2, 3, 5, 8, 9] a.sorted() # ERROR # however, min() and max() are only built-in functions a.min() # ERROR min(a) # ok -> 1 # unless you work with numpy, where min() and max() do exist :S import numpy as np n = np.array([5,2,4,9,1,7]) n.min() # ok -> 1
string.join ()
# I have to call .join() on a string to concatenate a list = confusing. # concatenating a list of strings ", ".join(["apple", "banana", "cherry"]) # 'apple, banana, cherry' # even uglier, when list is not a string ", ".join([str(s) for s in [1,2,3,4]]) # '1, 2, 3, 4'
Список списков
# The wrong way a = [[]] * 5 # [[], [], [], [], []] a[0].append(1) # [[1], [1], [1], [1], [1]] # The right way a = [[] for _ in range(5)]
‘IS’ и ‘==’ на INTS
# Internally some int objects are cached. When you compare 2 ints, you should use ==. # However, using 'is' can also work in some cases. x = 2000 y = 2000 x is y # False -> good, because this should not be allowed anyways. x = 5 y = 5 x is y # True -> But this works.... # See also # https://stackoverflow.com/questions/306313/is-operator-behaves-unexpectedly-with-integers
Вы нашли какие -нибудь интересные или забавные вещи в Python, которые смутили вас в первый раз, когда вы их увидели? Поделитесь ими в комментариях ниже.
Оригинал: “https://dev.to/r0f1/what-is-the-most-confusing-thing-to-you-in-python”