(翻译)30天学习Python👨‍💻第四天——数据类型3

477 阅读6分钟

30天学习Python👨‍💻第四天——数据类型3

在我分享我每天学习python的过程中,越来越明显的发现,同时学习和分享我对概念的理解能够帮助我构建知识体系。除此之外,另一个收获是从社会得到的认可❤️。

接着第三天,今天我们继续探索集合以及剩下的数据类型。

列表方法

和字符串一样,Python提供给了我们一些内置函数处理列表的数据。对象(这里是集合)通过.操作符调用这些方法。可以根据方法的类型对方法进行分类。

添加元素(append,insert,extend)

scores = [44,48,55,89,34]
scores.append(100) # 添加一个值到列表的尾部
print(scores) # [44, 48, 55, 89, 34, 100]
scores.insert(0, 34) # 在索引为0的值前面插入一个值
scores.insert(2, 44) # 在索引为2的值前面插入一个值
print(scores) # [34, 44, 44, 48, 55, 89, 34, 100]
scores.extend([23]) # Extend接受一个可迭代的(可循环的项)参数,并将它添加到列表尾部
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

删除元素(pop,remove,clear)

languages = ['C', 'C#', 'C++']
languages.pop()
print(languages) # ['C', 'C#']
languages.remove('C')
print(languages) # ['C#']
languages.clear()
print(languages) # []

获取索引和统计(index,count)

alphabets = ['a', 'b', 'c']
print(alphabets.index('a')) # 0 返回元素在列表中的索引
print(alphabets.count('b')) # 1 统计元素出现的个数

排序、反转和复制列表(sort,reverse,copy)

numbers = [1,4,6,3,2,5]
numbers.sort() # 对列表进行适当的排序,没有返回值
print(numbers) # [1, 2, 3, 4, 5, 6]

#Python也有一个内置的排序函数,返回一个新的数组
sorted_numbers = sorted(numbers) # 注意:这不是一个方法
print(sorted_numbers) # [1, 2, 3, 4, 5, 6]

numbers.reverse() # 反转列表
print(numbers) # [6, 5, 4, 3, 2, 1]

numbers_clone = numbers.copy() # 另一种方式是numbers[:]
print(numbers_clone) # [6, 5, 4, 3, 2, 1]

Python列表的所有方法

一些常用的列表用法

最后,我探索了一些列表常用用法,比如我刚刚提到的反转列表,将列表拼接为字符串,克隆

avengers = ['ironman', 'spiderman', 'antman', 'hulk']
cloned_avengers = avengers[::1] # 非常常用的方式(复制列表)
reversed_avengers = avengers[::-1] # 这样也是很常用的(逆序复制列表)
merge_avengers = ' '.join(avengers) # 将列表拼接为一个字符串
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)) # 快速生成特定范围内的列表
print(range_of_numbers) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
another_range = list(range(0,5)) # 指定范围的起始点和终止点
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] # 剩余的元素将储存在others变量中
print(a) # 1
print(others) # [2, 3, 4, 5]

first,*others,last= [😄,😋,😠,😔,😉]
print(first) # 😄
print(others) # ['😋', '😠', '😔']
print(last) # 😉

None

None在Python中是一种特殊的数据类型,它代表缺省值。在大多数的编程语言中,缺省值都用null表示。

Dictionaries(字典)

dictionary 或者dict是Python中的一种数据类型,它用键-值表示,包含一组无组织的数据集合。因此字典是一种数据结构,它以特定的格式存储数据。对比在JavaScript中,object是用key-value对来存储数据的。在dict中,key用字符串表示,而value可以是任意的数据类型。因为字典是没有顺序的,所以是分散的存储在内存中,而不像列表那样是按照顺序存储在内存中的。

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 为不存在的键设置默认值

我们可以使用别的方式来检查一个特定的键是否在一个字典中

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

有一些常用的字典方法,比如copyclearpopupdate

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'}) # 如果键不存在就增加
print(cat_copy) # {'name': 'Polo', 'greet': 'meow', 'health': 100, 'color': 'Black'}

Python中字典所有的方法

Tuples(元组)

元组是一种非常类似于列表的数据类型,但它们是不可变的,这意味着它的值是不可被修改的,也不能像列表那样进行排序。

my_tuple = (1,2,3) 
print(my_tuple[1]) # 2 值可以像列表一样被访问
print(1 in my_tuple) # True 检查列表中是否存在某元素

因为元组是不可变的,因此可以作为字典的键。

元组方法

像列表一样,我们可以对元组进行切片,因为切片可以返回一个新的元组而不会改变原来的元组。

colors = ('red', 'orange', 'blue', 'yellow')
new_colors = colors[1:4]
print(new_colors) # ('orange', 'blue', 'yellow')

color_1,*others = colors # 解构
print(color_1) # 'red'
print(others) # ['orange', 'blue', 'yellow']

print(len(colors)) # 4
print(colors.count('red')) # 1 
print(colors.index('orange')) # 1

Python中元组的所有方法

Sets(集合)

最后一种数据类型了 😋(除非出现了新的数据类型)

集合是一种数据结构,它存储的是一个无序的、元素是唯一的集合对象。在JavaScript中,也有一个Set的数据结构。

set_of_numbers = {1,2,3,4,5,5}
print(set_of_numbers) # {1,2,3,4,5}  (存储的值是唯一的)

这对移除邮箱地址列表中重复的地址是非常有用的。

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']

集合方法

集合内置的方法非常像我们小学时候学过的韦恩图。集合的内置方法非常重要,但我觉得没必要记住,需要的时候搜一下就可以了。

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) # 和上面方法的功能一样,是简便的写法 —— 求交集

print(set_a.intersection(set_b)) # {4, 5}
print(set_a & set_b) # 和上面方法功能一样 —— 求并集

set_a.discard(1)
print(set_a) # {2,3,4,5}

Python中元组的所有方法

到这里我们已经学完了Python中所有基本的数据类型。

Alt Text

明天我们的重点是流程控制和迭代或循环。

原文链接

[30 Days of Python 👨‍💻 - Day 4 - Data Types III](