Углубитесь в важные темы, код, ресурсы и реализации…

День 2: Основы Python с реализацией кода - Часть 2
В этом посте мы подробно рассмотрим основы Python (часть 2), которые вам следует знать.
Вы можете прочитать сообщение дня 1 здесь.
Вы можете прочитать сообщение о третьем дне здесь.
Списки Python
- Списки - один из самых универсальных типов данных в Python. Они используются для хранения нескольких элементов (однородных или неоднородных) в одной переменной.
- Поместите элементы в квадратные скобки []
- Элементы могут быть любого типа данных
- Списки определяются как объекты с типом данных «список».
- Элементы упорядочены, изменяемы и допускают повторяющиеся значения
- конструктор list () можно использовать при создании нового списка
- Чтобы получить доступ к значениям в списках, используйте квадратные скобки для сечения вместе с индексом, чтобы получить значение элемента, доступное по определенному индексу.
- Элементы внутри списка индексируются, первый элемент имеет индекс [0], второй элемент имеет индекс [1] и т. Д.
Пример -
var = [1, 2, «машина», «воскресенье», 3.14]
empty_list = []
items = list ((«яблоко», «банан», «виноград»))
Реализация -
#Create a List list_one = ["sunday","monday","tuesday","wednesday","thursday"] print(list_one)
Выход -
['sunday', 'monday', 'tuesday', 'wednesday', 'thursday']
Реализация -
#List Length print(len(list_one))
Выход -
5
Реализация -
# List with different data types list_two = ['abc',67,True,3.14,"female"] print(list_two)
Выход -
['abc', 67, True, 3.14, 'female']
Реализация -
#type() with List print(type(list_two))
Выход -
<class 'list'>
Реализация -
#list() constructor to make a List
list_cons = list(("hello","World","Beautiful","Day"))
print(list_cons)
Выход -
['hello', 'World', 'Beautiful', 'Day']
Реализация -
# nested list list_nest= ["hello",[8,4,6],['World']] print(list_nest)
Выход -
['hello', [8, 4, 6], ['World']]
Реализация -
#slice lists in Python : Use the slicing operator :(colon) list_one = ["sunday","monday","tuesday","wednesday","thursday"] print(list_one[1:4])
Выход -
['monday', 'tuesday', 'wednesday']
Реализация -
#Add/Change List Elements : use the assignment operator = to change #an item list_one = ["sunday","monday","tuesday","wednesday","thursday"] list_one[3] = 'friday' print(list_one)
Выход -
['sunday', 'monday', 'tuesday', 'friday', 'thursday']
Реализация -
# Appending and Extending lists in Python : Use the append() or #extend() method
list_one = ["sunday","monday","tuesday","wednesday","thursday"]
list_one.append('friday')
print(list_one)
#extend
list_one.extend(['saturday'])
print(list_one)
Выход -
['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday'] ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday']
Реализация -
# Concatenating and repeat lists : use + operator to concate two #lists and use * operator to repeat lists list_one = ["sunday","monday","tuesday","wednesday","thursday"] print(list_one + [0,1,2,3,4]) #repeat operation print(['a','b']*2)
Выход -
['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 0, 1, 2, 3, 4] ['a', 'b', 'a', 'b']
Реализация -
# Delete/Remove List Elements : delete one or more items or entire list using the keyword del
del list_one[2]
print(list_one)
#remove method : remove the given item or pop() method to remove an item at the given index location
list_one = ["sunday","monday","tuesday","wednesday","thursday"]
list_one.remove("tuesday")
print(list_one)
#pop method
list_one = ["sunday","monday","tuesday","wednesday","thursday"]
list_one.pop(2)
print("Pop result:", list_one)
Выход -
['sunday', 'monday', 'thursday'] ['sunday', 'monday', 'wednesday', 'thursday'] Pop result: ['sunday', 'monday', 'wednesday', 'thursday']
Реализация -
# index() method : Returns the index of the first matched item
list_one = ["sunday","monday","tuesday","wednesday","thursday"]
print(list_one.index("tuesday"))
Выход -
2
Реализация -
# sort() method: Sort items in a list in ascending order list_one = ["sunday","monday","tuesday","wednesday","thursday"] list_one.sort() print(list_one)
Выход -
['monday', 'sunday', 'thursday', 'tuesday', 'wednesday']
Реализация -
# reverse() : Reverse the order of items in the list list_one = ["sunday","monday","tuesday","wednesday","thursday"] list_one.reverse() print(list_one)
Выход -
['thursday', 'wednesday', 'tuesday', 'monday', 'sunday']
Реализация -
# copy(): Returns a shallow copy of the list list_one = ["sunday","monday","tuesday","wednesday","thursday"] list_two = list_one.copy() print(list_two)
Выход -
['sunday', 'monday', 'tuesday', 'wednesday', 'thursday']
Реализация -
#Membership : check if an item exists in a list or not, using the keyword in
list_one = ["sunday","monday","tuesday","wednesday","thursday"]
print('tuesday' in list_one)
Выход -
True
Реализация -
# insert() method : insert item at a desired location list_one = ["sunday","monday","tuesday","wednesday","thursday"] list_one.insert(2,'friday') print(list_one)
Выход -
['sunday', 'monday', 'friday', 'tuesday', 'wednesday', 'thursday']
Составить список
- В python понимание списков используется для создания нового списка на основе значений существующего списка наиболее элегантным и кратчайшим способом.
- Понимание списка состоит из выражения, за которым следует оператор for внутри квадратных [] скобок.
Одна из лучших статей, которые я прочитал для Структуры данных Python, автор Цзяхуэй Ван
Пример :
new_list = [x для x в списке 1, если «a» в x]
Реализация -
sqr = [2**x for x in range(20)] print(sqr)
Выход -
[1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144, 524288]
Словари Python
- В python словарь - это неупорядоченный набор значений данных, в котором значения данных хранятся в парах ключ: значение.
- Создается путем помещения последовательности элементов в фигурные {} фигурные скобки, разделенных ","
- Значения могут иметь любой тип данных и могут дублироваться, тогда как ключи неизменны и не могут повторяться.
- Может быть создано встроенной функцией dict ()
- Словари определяются как объекты с типом данных ‘dict
- Конструктор dict () можно использовать при создании нового dict
- Для доступа к значениям в dict используйте клавиши
- Формат ключевого значения делает словарь одним из наиболее оптимизированных и эффективных типов данных в Python.
Пример -
var = {‘first_day’: ‘sunday’, ‘second_day’: ‘monday’, ‘third_day’: ‘tuesday’}
empty_dict = {}
класс dict (** kwarg)
Реализация -
#Create a Dictionary
#empty dictionary
dict_emp = {}
#dict with items
dict_one = {0:'sunday', 1: 'monday', 2: 'tuesday', 3: 'wednesday', 4: 'thursday'}
print(dict_one)
Выход -
{0: 'sunday', 1: 'monday', 2: 'tuesday', 3: 'wednesday', 4: 'thursday'}
Реализация -
#Accessing Elements from Dictionary : Using keys or get() method
dict_one = {0:'sunday', 1: 'monday', 2: 'tuesday', 3: 'wednesday', 4: 'thursday'}
print(dict_one[1])
#get() method
print(dict_one.get(2))
Выход -
monday tuesday
Реализация -
# Length of Dictionary
dict_one = {0:'sunday', 1: 'monday', 2: 'tuesday', 3: 'wednesday', 4: 'thursday'}
print(len(dict_one))
Выход -
5
Реализация -
#Changing and Adding Dictionary elements: add new items or change the value of existing items using an = operator
dict_one = {0:'sunday', 1: 'monday', 2: 'tuesday', 3: 'wednesday', 4: 'thursday'}
#change element
dict_one[2] = 'friday'
print("After changing the element", dict_one)
#Add element
dict_one[5] = 'saturday'
print("After adding the element :", dict_one)
Выход -
After changing the element {0: 'sunday', 1: 'monday', 2: 'friday', 3: 'wednesday', 4: 'thursday'}
After adding the element : {0: 'sunday', 1: 'monday', 2: 'friday', 3: 'wednesday', 4: 'thursday', 5: 'saturday'}
Реализация -
#Removing elements from Dictionary : Use the pop() or popitem() #method
dict_one = {0:'sunday', 1: 'monday', 2: 'tuesday', 3: 'wednesday', 4: 'thursday'}
print(dict_one.pop(2))
#popitem : remove an arbitrary item and return (key,value)
print(dict_one.popitem())
Выход -
tuesday (4, 'thursday')
Реализация -
# remove all items : using clear method dict_one.clear() print(dict_one)
Выход -
{}
Реализация -
#fromkeys(seq[, t]): Returns a new dictionary with keys from seq and value equal to t
subjects = {}.fromkeys(['Computer Science','Space Science','Math','English'])
print(subjects)
Выход -
{'Computer Science': None, 'Space Science': None, 'Math': None, 'English': None}
Реализация -
#items() method : displays a list of dictionary's (key, value) tuple pairs
dict_one = {0:'sunday', 1: 'monday', 2: 'tuesday', 3: 'wednesday', 4: 'thursday'}
print(dict_one.items())
Выход -
dict_items([(0, 'sunday'), (1, 'monday'), (2, 'tuesday'), (3, 'wednesday'), (4, 'thursday')])
Реализация -
#keys() method : displays a list of all the keys in the dictionary
dict_one = {0:'sunday', 1: 'monday', 2: 'tuesday', 3: 'wednesday', 4: 'thursday'}
print(dict_one.keys())
Выход -
dict_keys([0, 1, 2, 3, 4])
Реализация -
#values() method : displays a list of all the values in the dictionary
dict_one = {0:'sunday', 1: 'monday', 2: 'tuesday', 3: 'wednesday', 4: 'thursday'}
print(dict_one.values())
Выход -
dict_values(['sunday', 'monday', 'tuesday', 'wednesday', 'thursday'])
Реализация -
#setdefault() method : returns the value of a key. If not there, it inserts key with a value to the dictionary
dict_one = {0:'sunday', 1: 'monday', 2: 'tuesday', 3: 'wednesday', 4: 'thursday'}
element = dict_one.setdefault(3)
print(element)
#If key not present
element = dict_one.setdefault(6)
print("If key is not present:", dict_one.items())
Выход -
wednesday If key is not present: dict_items([(0, 'sunday'), (1, 'monday'), (2, 'tuesday'), (3, 'wednesday'), (4, 'thursday'), (6, None)])
Реализация -
#Nested Dictionaries
people = {"subject": {0:"Maths",1:"English",3:"Science"},
"marks": {0:42,1:36,2: 78},
"Age": {0:12,1:34,2:19}
}
#print(people["marks"][0])
print(people["Age"][0])
Выход -
42
Реализация -
#sorted(): Return a new sorted list of keys in the dictionary
dict_one = {0:'sunday', 1: 'monday', 2: 'tuesday', 3: 'wednesday', 4: 'thursday'}
print(sorted(dict_one))
Выход -
[0, 1, 2, 3, 4]
Реализация -
#Iterate through dictionay
dict_one = {0:'sunday', 1: 'monday', 2: 'tuesday', 3: 'wednesday', 4: 'thursday'}
for i in dict_one.items():
print(i)
Выход -
(0, 'sunday') (1, 'monday') (2, 'tuesday') (3, 'wednesday') (4, 'thursday')
Реализация -
# Dictionary Comprehension
cubes = {x: x*x*x for x in range(10)}
print(cubes)
Выход -
{0: 0, 1: 1, 2: 8, 3: 27, 4: 64, 5: 125, 6: 216, 7: 343, 8: 512, 9: 729}
Реализация -
# update() method : updates the dictionary with the elements from
# another dictionary object or from any other key/value pairs
dict1 ={0:"zero",4:"four",5:"five"}
dict2={2:"two"}
# updates the value of key 2
dict1.update(dict2)
print(dict1)
Выход -
{0: 'zero', 4: 'four', 5: 'five', 2: 'two'}
Реализация -
# Membership Test : check if a key is in a dictionary or not using #the keyword in
dict_one = {0:'sunday', 1: 'monday', 2: 'tuesday', 3: 'wednesday', 4: 'thursday'}
print(0 in dict_one.keys())
Выход -
True
День 3: Основы Python, часть 3 - скоро! Подпишитесь / следите и следите за обновлениями :)
Продолжайте учиться и кодировать :)