801 - 850 Flashcards
set.issubset()
позволяет проверить находится ли каждый элемент множества sets в последовательности other. Метод возвращает True, если множество sets является подмножеством итерируемого объекта other, если нет, то вернет False.
x = {"a", "b", "c"} y = {"f", "e", "d", "c", "b", "a"} z = x.issubset(y) print(z) 👉 True
set.difference_update()
method removes the items that exist in both sets.
x = {"apple", "banana", "cherry"} y = {"google", "microsoft", "apple"} x.difference_update(y) print(x) 👉 {'cherry', 'banana'}
set.difference()
method returns a set that contains the difference between two sets.Meaning: The returned set contains items that exist only in the first set, and not in both sets.
x = {"apple", "banana", "cherry"} y = {"google", "microsoft", "apple"} z = x.difference(y) print(z) 👉 {'banana', 'cherry'}
set.add()
one item to a set use the add() method.
thisset = {"apple", "banana", "cherry"} thisset.add("orange") print(thisset) 👉 {'apple', 'cherry', 'banana', 'orange'}
list.extend()
method adds the specified list elements (or any iterable) to the end of the current list.
fruits = ['apple', 'banana', 'cherry'] cars = ['Ford', 'BMW', 'Volvo'] fruits.extend(cars) print(fruits) 👉 ['apple', 'banana', 'cherry', 'Ford', 'BMW', 'Volvo']
list.sorted(iterable, *, key=None, reverse=False)
🎯 iterable - объект, поддерживающий итерирование
🎯 key=None - пользовательская функция, которая применяется к каждому элементу последовательности
🎯 reverse=False - порядок сортировки
function returns a sorted list of the specified iterable object. You can specify ascending or descending order. Strings are sorted alphabetically, and numbers are sorted numerically.
line = 'This is a test string from Andrew' x = sorted(line.split(), key=str.lower) print(x) 👉 ['a', 'Andrew', 'from', 'is', 'string', 'test', 'This']
student = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)] x = sorted(student, key=lambda student: student[2]) print(x) 👉 [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
data = [('red', 1), ('blue', 1), ('red', 2), ('blue', 2)] x = sorted(data, key=lambda data: data[0]) print(x) 👉 [('blue', 1), ('blue', 2), ('red', 1), ('red', 2)]
a = ("b", "g", "a", "d", "f", "c", "h", "e") x = sorted(a) print(x) 👉 ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
a = (1, 11, 2) x = sorted(a) print(x) 👉 [1, 2, 11]
list.reverse()
method reverses the sorting order of the elements. поменять местами список
fruits = ['apple', 'banana', 'cherry'] fruits.reverse() print(fruits) 👉 ['cherry', 'banana', 'apple']
areas = ["hallway", 11.25, "kitchen", 18.0, "living room", 20.0, "bedroom", 10.75, "bathroom", 9.50] upstairs = areas[:-5:-1] upstairs_2 = areas[-4:] print(upstairs) 👉 [9.5, 'bathroom', 10.75, 'bedroom'] print(upstairs_2) 👉 ['bedroom', 10.75, 'bathroom', 9.5]
list.sort()
method that will sort the list alphanumerically, ascending, by default.
thislist = ["orange", "mango", "kiwi", "pineapple", "banana"] thislist.sort() print(thislist) 👉 ['banana', 'kiwi', 'mango', 'orange', 'pineapple']
list.remove()
method removes the specified item.
thislist = ["apple", "banana", "cherry"] thislist.remove("banana") print(thislist) 👉 ['apple', 'cherry']
list.insert()
вставить method inserts the specified value at the specified position.
fruits = ['apple', 'banana', 'cherry'] fruits.insert(1, "orange") print(fruits) 👉 ['apple', 'orange', 'banana', 'cherry']
list.len()
function returns the number of items in an object.
mylist = ["apple", "orange", "cherry"] x = len(mylist) print(x) 👉 3
x = len("Hello") print(x) 👉 5
list.pop()
method removes the element at the specified position.
fruits = ['apple', 'banana', 'cherry'] fruits.pop(1) print(fruits) 👉 ['apple', 'cherry']
list.index()
method returns the position at the first occurrence of the specified value.
fruits = ['apple', 'banana', 'cherry'] x = fruits.index("cherry") print(x) 👉 2
list.count()
method returns the number of elements with the specified value.
fruits = ["apple", "banana", "cherry", "cherry"] x = fruits.count("cherry") print(x) 👉 2
list.clear()
method removes all the elements from a list.
fruits = ["apple", "banana", "cherry"] fruits.clear() print(fruits) 👉 []
list.append()
method appends an element to the end of the list.
fruits = ["apple", "banana", "cherry"] fruits.append("orange") print(fruits) 👉 ['apple', 'banana', 'cherry', 'orange']
exec(object, globals=None, locals=None)
🎯 object - строка кода, либо объект кода
🎯 globals - словарь глобального пространства, относительно которого следует исполнить код
🎯 locals - объект-отображение (например dict), локальное пространство, в котором следует исполнить код.
поддерживает динамическое выполнение кода Python и принимает большие блоки кода, в отличие от eval(). Передаваемый функции код должен быть либо строкой, либо объектом кода, например сгенерированный функцией compile(). Если это строка, строка анализируется как набор операторов Python, который затем выполняется.
x = 'name = "John"\nprint(name)' exec(x) 👉 John
y = 'print("5 + 10 =", (5+10))' exec(y) 👉 5 + 10 = 15
prog = 'for x in range(9):\n res = x*x\n print(res)' exec(prog) 👉 0 👉 1 👉 4 👉 9 👉 16 👉 25 👉 36 👉 49 👉 64
dict.values()
dict.values
method returns a view object. The view object contains the values of the dictionary, as a list.
car = { "brand": "Ford", "model": "Mustang", "year": 1964 } x = car.values() print(x) 👉 dict_values(['Ford', 'Mustang', 1964])
dict.update()
method inserts the specified items to the dictionary.
car = { "brand": "Ford", "model": "Mustang", "year": 1964 } car.update({"color": "White"}) print(car) 👉 {'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'White'}
dict.keys()
method returns a view object. The view object contains the keys of the dictionary, as a list.
car = { "brand": "Ford", "model": "Mustang", "year": 1964 } x = car.keys() print(x) 👉 dict_keys(['brand', 'model', 'year'])