Python有一些内置的数据结构。如果您想知道数据结构是什么,它只不过是一种存储数据和使用特定方法来检索或操作数据的方法。我们之前已经遇到过此清单; 现在我们将深入探讨。
Lists
>>> a = [23, 45, 1, -3434, 43624356, 234]
>>> a.append(45)
>>> a
[23, 45, 1, -3434, 43624356, 234, 45]
起初我们创建了一个列表a。然后在列表的末尾添加45,我们称之为a.append(45)方法。您可以看到列表末尾添加了45。有时需要在列表中的任何位置插入数据,因为我们有insert()方法。
>>> a.insert(0, 1) # 1 added at the 0th position of the list
>>> a
[1, 23, 45, 1, -3434, 43624356, 234, 45]
>>> a.insert(0, 111)
>>> a
[111, 1, 23, 45, 1, -3434, 43624356, 234, 45]
count(s)将返回s在列表中的次数。在这里,我们将检查列表中有多少次45。
>>> a.count(45)
2
如果要从列表中删除任何特定值,则必须使用remove()方法。
>>> a.remove(234)
>>> a
[111, 1, 23, 45, 1, -3434, 43624356, 45]
现在反转整个列表
>>> a.reverse()
>>> a
[45, 43624356, -3434, 1, 45, 23, 1, 111]
我们可以存储在列表中任何东西,所以首先我们要添加另一个列表 b中的 一个 ; 然后我们将学习如何将b的值添加 到 a中。
>>> b = [45, 56, 90]
>>> a.append(b)
>>> a
[45, 43624356, -3434, 1, 45, 23, 1, 111, [45, 56, 90]]
>>> a[-1]
[45, 56, 90]
>>> a.extend(b) #To add the values of b not the b itself
>>> a
[45, 43624356, -3434, 1, 45, 23, 1, 111, [45, 56, 90], 45, 56, 90]
>>> a[-1]
90
上面你可以看到我们如何使用a.extend()方法扩展列表。要排序任何列表,我们有sort()方法。如果列表中的元素是可比较的,该sort()方法才有效。我们将从列表中删除列表b然后排序。
>>> a.remove(b)
>>> a
[45, 43624356, -3434, 1, 45, 23, 1, 111, 45, 56, 90]
>>> a.sort()
>>> a
[-3434, 1, 1, 23, 45, 45, 45, 56, 90, 111, 43624356]
您还可以使用del关键字删除列表中任何特定位置的元素。
>>> del a[-1]
>>> a
[-3434, 1, 1, 23, 45, 45, 45, 56, 90, 111]
使用Lists作为堆栈和队列
堆栈通常称为LIFO(后进先出)结构。这意味着数据将在最后进入,最后的数据将首先出现。最简单的例子可以是一侧封闭管道中的几个弹珠。因此,如果你想从中取出弹珠,你必须从插入最后一块弹珠的那一端开始。在代码中实现相同
>>> a = [1, 2, 3, 4, 5, 6]
>>> a
[1, 2, 3, 4, 5, 6]
>>> a.pop()
6
>>> a.pop()
5
>>> a.pop()
4
>>> a.pop()
3
>>> a
[1, 2]
>>> a.append(34)
>>> a
[1, 2, 34]
我们在pop()上面学到了一种新方法。pop(i)将从列表中取出第i个数据。
在我们的日常生活中,我们肯定遇到许多排队,例如在售票柜台或图书馆或任何超市的计费部分。队列是一种数据结构,您可以在其中添加更多数据并从头开始取出数据。这就是它被称为FIFO(先进先出)的原因。
>>> a = [1, 2, 3, 4, 5]
>>> a.append(1)
>>> a
[1, 2, 3, 4, 5, 1]
>>> a.pop(0)
1
>>> a.pop(0)
2
>>> a
[3, 4, 5, 1]
要取出列表的第一个元素,我们使用a.pop(0)。
列表推导
列表推导提供了创建列表的简明方法。每个列表推导由一个表达式后跟一个for子句,然后是零个或多个for或if子句组成。结果将是通过在其后面的for和if子句的上下文中评估表达式而得到的列表。
例如,如果我们想要从另一个列表的平方值中列出一个列表,那么
>>> a = [1, 2, 3]
>>> [x ** 2 for x in a]
[1, 4, 9]
>>> z = [x + 1 for x in [x ** 2 for x in a]]
>>> z
[2, 5, 10]
在第二种情况下,我们在同一行中使用了两个列表推导。
Tuples
元组是用逗号分隔的数据。
>>> a = 'Fedora', 'Debian', 'Kubuntu', 'Pardus'
>>> a
('Fedora', 'Debian', 'Kubuntu', 'Pardus')
>>> a[1]
'Debian'
>>> for x in a:
... print(x, end=' ')
...
Fedora Debian Kubuntu Pardus
您还可以将任何元组的值解压缩为变量,例如
>>> divmod(15,2)
(7, 1)
>>> x, y = divmod(15,2)
>>> x
7
>>> y
1
元组是不可变的,这意味着你不能在元组内部添加/编辑任何值。这是另一个例子
>>> a = (1, 2, 3, 4)
>>> del a[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object doesn't support item deletion
如您所见,当我们尝试删除元组中的值时,Python会出错。
要创建仅包含一个值的元组,请键入尾随逗号。
>>> a = (123)
>>> a
123
>>> type(a)
<class 'int'>
>>> a = (123, ) #Look at the trailing comma
>>> a
(123,)
>>> type(a)
<class 'tuple'>
使用内置函数type()可以知道任何变量的数据类型。还记得我们用来查找任何序列长度的len()函数吗?
>>> type(len)
<class 'builtin_function_or_method'>
Sets
Sets是另一种没有重复项的数据结构。我们可以在集合上应用数学集合运算。
>>> a = set('abcthabcjwethddda')
>>> a
{'a', 'c', 'b', 'e', 'd', 'h', 'j', 't', 'w'}
以及设置操作的一些示例
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a # unique letters in a
{'a', 'r', 'b', 'c', 'd'}
>>> a - b # letters in a but not in b
{'r', 'd', 'b'}
>>> a | b # letters in either a or b
{'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
>>> a & b # letters in both a and b
{'a', 'c'}
>>> a ^ b # letters in a or b but not both
{'r', 'd', 'b', 'm', 'z', 'l'}
添加或弹出集合中的值
>>> a
{'a', 'c', 'b', 'e', 'd', 'h', 'j', 'q', 't', 'w'}
>>> a.add('p')
>>> a
{'a', 'c', 'b', 'e', 'd', 'h', 'j', 'q', 'p', 't', 'w'}
Dictionaries
字典是无序的一组键:值对,其中键是唯一的。我们使用{}括号声明字典。我们使用字典来存储任何特定键的数据,然后检索它们。
>>> data = {'kushal':'Fedora', 'kart_':'Debian', 'Jace':'Mac'}
>>> data
{'kushal': 'Fedora', 'Jace': 'Mac', 'kart_': 'Debian'}
>>> data['kart_']
'Debian'
我们可以简单地添加更多数据
>>> data['parthan'] = 'Ubuntu'
>>> data
{'kushal': 'Fedora', 'Jace': 'Mac', 'kart_': 'Debian', 'parthan': 'Ubuntu'}
删除任何特定键:值对
>>> del data['kushal']
>>> data
{'Jace': 'Mac', 'kart_': 'Debian', 'parthan': 'Ubuntu'}
要检查字典中是否有任何键,您可以使用in keyword。
>>> 'Soumya' in data
False
您必须记住,任何可变对象都不能成为密钥,这意味着您不能将列表用作密钥。
dict()可以从键,值对的元组创建字典。
>>> dict((('Indian','Delhi'),('Bangladesh','Dhaka')))
{'Indian': 'Delhi', 'Bangladesh': 'Dhaka'}
如果要循环使用dict,请使用items()方法。
>>> data
{'Kushal': 'Fedora', 'Jace': 'Mac', 'kart_': 'Debian', 'parthan': 'Ubuntu'}
>>> for x, y in data.items():
... print("%s uses %s" % (x, y))
...
Kushal uses Fedora
Jace uses Mac
kart_ uses Debian
parthan uses Ubuntu
很多时候我们想要向字典中的值添加更多数据,如果密钥不存在,那么我们添加一些默认值。您可以使用dict.setdefault(键,默认值)有效地执行此操作。
>>> data = {}
>>> data.setdefault('names', []).append('Ruby')
>>> data
{'names': ['Ruby']}
>>> data.setdefault('names', []).append('Python')
>>> data
{'names': ['Ruby', 'Python']}
>>> data.setdefault('names', []).append('C')
>>> data
{'names': ['Ruby', 'Python', 'C']}
当我们尝试获取不存在的键的值时,我们得到KeyError。我们可以使用dict.get(key,default)在它们之前不存在键时获取默认值。
>>> data['foo']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'foo'
>>> data.get('foo', 0)
0
如果要循环遍历列表(或任何序列)并同时获取迭代次数,则必须使用enumerate()。
>>> for i, j in enumerate(['a', 'b', 'c']):
... print(i, j)
...
0 a
1 b
2 c
您可能还需要同时迭代两个序列,为此使用zip()函数。
>>> a = ['Pradeepto', 'Kushal']
>>> b = ['OpenSUSE', 'Fedora']
>>> for x, y in zip(a, b):
... print("%s uses %s" % (x, y))
...
Pradeepto uses OpenSUSE
Kushal uses Fedora
students.py
在这个例子中,你必须把学生的数量作为输入,然后要求三个科目的标记为“物理”,“数学”,“历史”,如果任何学生的总分少于120则打印他失败,否则说过了。
#!/usr/bin/env python3
n = int(input("Enter the number of students:"))
data = {} # here we will store the data
languages = ('Physics', 'Maths', 'History') #all languages
for i in range(0, n): #for the n number of students
name = input('Enter the name of the student %d: ' % (i + 1)) #Get the name of the student
marks = []
for x in languages:
marks.append(int(input('Enter marks of %s: ' % x))) #Get the marks for languages
data[name] = marks
for x, y in data.items():
total = sum(y)
print("%s 's total marks %d" % (x, total))
if total < 120:
print("%s failed :(" % x)
else:
print("%s passed :)" % x)
输出
$ ./students.py
Enter the number of students:2
Enter the name of the student 1: Babai
Enter marks of Physics: 12
Enter marks of Maths: 45
Enter marks of History: 40
Enter the name of the student 2: Tesla
Enter marks of Physics: 99
Enter marks of Maths: 98
Enter marks of History: 99
Babai 's total marks 97
Babai failed :(
Tesla 's total marks 296
Tesla passed :)
欢迎大家关注公众号:「Python精选」,关注公众号,回复「1024」你懂得,免费领取 6 本经典Python编程书籍。关注我,与 10 万程序员一起进步。每天更新Python干货哦,期待你的到来!







网友评论