Это вторая часть серии. для части 1 нажмите здесь
Python имеет четыре основных встроенных структуры данных. Это списки, кортежи, наборы, словари.
Списки
- Список - это упорядоченная последовательность элементов.
- Все элементы в списке не обязательно должны быть одного типа.
- Списки изменяемые. означает, что значение списка может быть изменено или удалено.
emptylist = [] #to create a empty list mylst = [1,3.5,'abc',89] #basic list syntax lsts = [[1,2],[3,4]] #list of lists or multi dimensional list len(lst) #gives the length of a list
добавить, вставить и расширить
lst = [1,2,3] lst2 = [4,5] lst.append(value) #appends(atlast) value to the list lst.insert(x, ele) #add element ele at location x lst.append(lst2) #appends lst2 at the end of elements in lst i.e; [1,2,3,[4,5]] lst.extend(lst2) #appends elements of lst2 at the end of elements in lst [1,2,3,4,5] lists can also be extend by using ‘+’ #newlst = lst+lst2
del, pop, удалить и очистить
del lst[i]
#deletes item based on index i and it doesn’t return that deleted item
a = lst.pop(i) #pops an item and returns that item to a
lst.remove(ele) #removes first occurrence of ele in a list
lst.clear() #Remove all items from the list. Equivalent to del a[:]
перевернуть, отсортировать и отсортировать
lst.reverse() #reverses the list numbers = [3,1,6,2,8] sorted_lst = sorted(numbers) print(sorted_lst) #[1,2,3,6,8] - sorted in ascending order print(numbers) #[3,1,6,2,8] - original list remains unchanged sorted(numbers, reverse=True) #sorts in descending order(function) lst.sort() #sorts (method) the list and stored in itself unlike sorted function cannot sort list with elements of incomparable data types such as the list [1,2,’b’,5,’a’] #results in type error
строка для списка
s = “one,two,three” #s is a string slst = s.split(,) #default split is white character: space or tab (here it is comma) print(slst) #[‘one’,’two’,’three’]
Нарезка
lst[-1] #last element using negative indexing list slicing #lst[start : end : step-size] numbers[0:4] #from index 0 to index 3
счет и цикл
marks = [72,67,92,72,85] marks.count(72) #2 #frequency(number of times it has occured) of ele in a lst for ele in marks: print(ele)
понимание списка
provide a concise way to create lists squares = [i**2 for i in range(5)] #i² for all, i=0 to 4 print(squares) #[0,1,4,9,16]
Кортежи
- Кортеж - это упорядоченная последовательность элементов, аналогичная списку.
- Единственная разница в том, что кортежи неизменяемые. это означает, что однажды созданные кортежи не могут быть изменены.
emptytuple = () #creation of empty tuple t = (1,’raju’,28,’abc’) #basic tuple syntax tl = (1,(2,3,4),[1,’abc’,3]) #nested tuple
общая ошибка при использовании кортежа и строки
t = (‘harsha’) #it is a string (or) t = “harsha” t = (‘harsha’,) #it is a tuple (or) t = “harsha”,
- индексация аналогична спискам t [i]
- нарезка аналогична спискам t [:]
в отличие от списков кортежи неизменяемы (мы не можем изменить или удалить)
t[2] = ‘x’ #TypeError: ‘tuple’ object does not support item assignment but we can change a list which is inside a tuple tl[2][0] = 5
конкатенация, del, index
t = (1,2,3)+(4,5,6) #concatenating tuples t = ((‘sri’,)*3) #repeat the elements in a tuple (‘sri’,’sri’,’sri’) del t #delete entire tuple t = (1,2,3,1,3,3,4,1) t.index(3) #2 — return the index of first occurrence of 3
другие базовые функции
len(t) sorted(t) max(t) min(t) sum(t)
Наборы
- Набор представляет собой неупорядоченный (не может быть проиндексирован) набор уникальных (без дубликатов) элементов.
- Сам набор изменяемый. мы можем добавлять или удалять элементы из него.
#set doesn’t allow duplicates s = {1,2,3,1,4} print(s) #{1,2,3,4} s = set() #empty set
добавить, обновить
s = {1,3} s.add(2) #add element into set s print(s) #{1,2,3} s.update([5,6,1]) #adds multiple elements at a time print(s) #{1,2,3,5,6} s.update([list],{set}) also possible
Discard, pop, clear
s.discard(ele) #ele is removed from the set s if it present else do nothing s.remove(ele) #ele is removed from the set s if it present else throws an error s.pop() #remove random element s.clear() #removes all the elements from the set
установить операции
#Union set1 | set2 or set1.union(set2) #Intersection set1 & set2 or set1.intersection(set2) #Set difference set1 — set2 or set1.difference(set2) #symm difference set1 ^ set2 or set1.symmetric_difference(set2) #subset set1.issubset(set2) #True or False
Неизменяемый набор не имеет метода добавления или удаления элементов.
замороженные наборы
изменяемые наборы не могут быть хешированы, поэтому их нельзя использовать в качестве ключей dict. с другой стороны, frozensets хешируются и могут использоваться как ключи к dict.
while tuples are immutable lists, frozen sets are immutable sets setf = frozenset([1,2,3,4])
Словари
- Словарь - это неупорядоченный набор пар "ключ-значение".
- Словари изменяемы.
It is like a hash table, has a key: value pair my_dict = {} or my_dict = dict() #empty dictionary #dictionary with integer keys my_dict = {1: ‘abc’, 2: ‘xyz’} #dictionary with mixed keys my_dict = {‘name’: ‘harsha’, 1: [‘abc’, ‘xyz’]}
доступ к словарям
my_dict[key] #gives error if key is invalid my_dict.get(key) #doesn’t give error and shows None if key is invalid my_dict[key] = value #adds new key: val pair
pop, popitem, del, clear
my_dict.pop(key) #remove element with the given key my_dict.popitem() #remove any arbitrary key — no parameters del my_dict[key] #remove element with the given key my_dict.clear() #removes entire dictionary
элементы, ключи, значения
subjects = {2:4, 3:9, 4:16, 5:25} print(subjects.items()) #return a new view of the dictionary items (key, value) as dict_items([(2, 4), (3, 9), (4, 16), (5, 25)]) print(subjects.keys()) #return a new view of the dictionary keys dict_keys([2, 3, 4, 5]) print(subjects.values()) #return a new view of the dictionary values dict_values([4, 9, 16, 25])
понимание словаря
#Creating a new dictionary with only pairs where the value is larger than 2 d = {‘a’: 1, ‘b’: 2, ‘c’: 3, ‘d’: 4} new_dict = {k:v for k, v in d.items() if v > 2} print(new_dict) #{‘c’: 3, ‘d’: 4}
Спасибо за чтение. Ваше здоровье :)