30 天 Python 学习 - 第 4 天 - 数据类型 III
随着我每天分享 Python 学习进度,我越来越清晰地意识到,学习和分享并同时解释概念有助于进一步巩固基础。另一个好处是来自社区的热爱 ❤️
从第三天离开的地方开始,我今天继续探索列表和剩余的数据类型。
列表上的操作
与字符串类似,Python 也提供了一些内置方法来对列表数据类型执行操作。同样,这些方法.在对象(此处为列表)的运算符之后调用。这些操作可以根据其类型进行分类。
- 向列表添加项目(附加、插入、扩展)
scores = [44,48,55,89,34]
scores.append(100) # Append adds a new item to the end
print(scores) # [44, 48, 55, 89, 34, 100]
scores.insert(0, 34) # Inserts 34 to index 0
scores.insert(2, 44) # Inserts 44 to index 2
print(scores) # [34, 44, 44, 48, 55, 89, 34, 100]
scores.extend([23]) # Extend takes an iterable (loopable items) and adds to end of list
print(scores) # [34, 44, 44, 48, 55, 89, 34, 100, 23]
scores.extend([12,10])
print(scores) # [34, 44, 44, 48, 55, 89, 34, 100, 23, 12, 10]
这里有一点小问题。这些方法会将项目就地添加到列表中,并且不返回任何值。
scores = [44,48,55,89,34]
newScores = scores.append(100)
print(newScores) # None
newScores = scores.insert(0,44)
print(newScores) # None
- 从列表中删除项目(弹出、删除、清除)
languages = ['C', 'C#', 'C++']
languages.pop()
print(languages) # ['C', 'C#']
languages.remove('C')
print(languages) # ['C#']
languages.clear()
print(languages) # []
- 获取索引并计数(索引,计数)
alphabets = ['a', 'b', 'c']
print(alphabets.index('a')) # 0 (Returns the index of the element in list
print(alphabets.count('b')) # 1 (counts the occurence of an element
- 排序、反转和复制列表
numbers = [1,4,6,3,2,5]
numbers.sort() # Sorts the list items in place and returns nothing
print(numbers) # [1, 2, 3, 4, 5, 6]
#Python also has a built in sorting function that returns a new list
sorted_numbers = sorted(numbers) # note - this is not a method
print(sorted_numbers) # [1, 2, 3, 4, 5, 6]
numbers.reverse() # reverse the indices in place
print(numbers) # [6, 5, 4, 3, 2, 1]
numbers_clone = numbers.copy() # another approach is numbers[:]
print(numbers_clone) # [6, 5, 4, 3, 2, 1]
一些常见的列表模式
最后,我探索了一些经常用于列表的常见模式,例如我已经提到的反转、将列表连接到字符串和克隆
avengers = ['ironman', 'spiderman', 'antman', 'hulk']
cloned_avengers = avengers[::1] # very commonly used pattern
reversed_avengers = avengers[::-1] # discussing again because it is also very common
merge_avengers = ' '.join(avengers) # used to join list into string
print(cloned_avengers) # ['ironman', 'spiderman', 'antman', 'hulk']
print(reversed_avengers) # ['hulk', 'antman', 'spiderman', 'ironman']
print(merge_avengers) # ironman spiderman antman hulk
range_of_numbers = list(range(10)) # quickly generates a list of specific range
print(range_of_numbers) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
another_range = list(range(0,5)) # with start stop
print(another_range) # [0, 1, 2, 3, 4]
列表解包
解包列表是个很棒的功能。它让我想起了 JavaScript 中的数组析构,也非常酷。
first,second,third = ['tesla','ford','ferarri']
print(first) # tesla
print(second) # second
print(third) # ferarri
a,*others = [1,2,3,4,5] # remaining values are stored in others
print(a) # 1
print(others) # [2, 3, 4, 5]
first,*others,last= [😄,😋,😠,😔,😉]
print(first) # 😄
print(others) # ['😋', '😠', '😔']
print(last) # 😉
我希望我能够展示一些解包列表的用例。
没有任何
None 是 Python 中一种特殊的数据类型,表示没有值。在大多数其他编程语言中,它通常被称为null。
字典
字典dict是 Python 中的一种数据类型,它包含以键值对形式存在的无序数据集合。因此,字典是一种以特定格式存储数据的数据结构。在我的理解中,我将其与 JavaScript 进行了比较,object在 JavaScript 中,我们将数据存储在键值对中。字典的键dict由字符串表示,值可以包含任何数据类型。可以使用相应的键访问值。由于字典没有任何顺序,它们分散在内存中,这与列表不同,列表在内存中按顺序存储。
user = {'name': 'Max', 'age': 40, 'married': False}
print(user['name']) # Max
print(user['married']) # False
字典键
我提到过,字典中的键需要是string数据类型。其实,这并不完全正确。dict键可以是任何不可变的数据类型。此外,键必须是唯一的。如果字典中有多个相同的键,则这些值会被覆盖。这也称为碰撞。
abstract = {
'first': 123,
True: 'hello',
777: [1,3,4,5]
}
print(abstract['first']) # 123
print(abstract[True]) # 'hello
print(abstract[777]) # [1,3,4,5]
sample = {
'username': 'hisenberg',
'username': 'james'
}
print(sample['username']) # james
字典方法
检查错误是一种很好的编程习惯,因为错误可能会中断程序的执行。在字典的上下文中,如果我们尝试访问一个不存在的键,Python 会抛出错误并停止程序的执行。这通常不是我们想要的,所以有一个内置的字典方法来处理这个问题。
house = {
'rooms' : 4,
'occupants': 2,
'doors': 6
}
print(house['windows']) # KeyError: 'windows'
#instead
print(house.get('windows')) # None
print(house.get('windows', 5)) # 5 (This sets a default value if no value is found)
还有其他一些方法可以检查字典中是否存在特定的键或值
user = {'name': 'Raghav', 'age': 20, 'country': 'India'}
print('name' in user.keys()) # True
print('gender' in user.keys()) # False
print('Raghav' in user.values()) # True
其他一些有用的字典方法是copy、clear、pop、update
cat = {
'name': 'Tom',
'greet': 'meow',
'health': 100
}
cat_copy = cat.copy()
print(cat_copy) # {'name': 'Tom', 'greet': 'meow', 'health': 100}
cat.pop('name')
print(cat) # {'greet': 'meow', 'health': 100}
cat.clear()
print(cat) # {}
cat_copy.update({'name': 'Polo'})
print(cat_copy) # {'name': 'Polo', 'greet': 'meow', 'health': 100}
cat_copy.update({'color': 'Black'}) # adds key value if not present
print(cat_copy) # {'name': 'Polo', 'greet': 'meow', 'health': 100, 'color': 'Black'}
元组
元组数据类型与列表非常相似,但它们是不可变的,这意味着它们的值不能被修改,也不能像列表那样进行排序。
my_tuple = (1,2,3) # Can be any no of items
print(my_tuple[1]) # 2 (Values can be accessed just like lists)
print(1 in my_tuple) # True (Checks if element is present)
由于元组是不可变的,因此它们也可以用作字典中的键。
对元组的操作
就像列表一样,我们可以对元组进行切片,因为切片会返回一个新的副本并且不会改变原始数据。
colors = ('red', 'orange', 'blue', 'yellow')
new_colors = colors[1:4]
print(new_colors) # ('orange', 'blue', 'yellow')
color_1,*others = colors # unpacking!
print(color_1) # 'red'
print(others) # ['orange', 'blue', 'yellow']
print(len(colors)) # 4
print(colors.count('red')) # 1
print(colors.index('orange')) # 1
套
最后是最后一种数据类型😋(除非旅途中出现新的东西)。
集合是一种存储无序唯一对象集合的数据结构。在我的 JavaScript 世界中,我记得也存在一个 Set 数据结构,所以它符合我的思维模型。
set_of_numbers = {1,2,3,4,5,5}
print(set_of_numbers) # {1,2,3,4,5} (Only unique values are stored)
这对于从电子邮件列表中删除重复的电子邮件地址非常有帮助
emails = ['samantha@hey.com', 'rock@hey.com', 'samantha@hey.com']
emails_set = set(emails)
unique_emails = list(emails_set)
print(unique_emails) # ['rock@hey.com', 'samantha@hey.com']
对集合的操作
集合的内置方法执行的操作与我们在小学数学课上学到的维恩图完全类似。以下是其中一些方法。我觉得没必要死记硬背,因为集合本身就是最重要的。这些方法可以随时在 Google 上搜索。
set_a = {1,2,3,4,5}
set_b = {4,5,6,7,8}
print(set_a.union(set_b)) # {1, 2, 3, 4, 5, 6, 7, 8}
print(set_a | set_b) # same as above just a compact syntax
print(set_a.intersection(set_b)) # {4, 5}
print(set_a & set_b) # same as above
set_a.discard(1)
print(set_a) # {2,3,4,5}
Python Set 方法
哦天哪!终于完成了对 Python 数据基本构建块的学习,并且对其数据类型有了基本的了解。
明天的重点是学习 Python 中的条件流和迭代(循环)。我现在很兴奋。希望你也喜欢学习这个功能😃
祝你过得愉快!
鏂囩珷鏉ユ簮锛�https://dev.to/arindamdawn/30-days-of-python-day-4-4lle
