内置数据结构
-
list
Python内置的一种数据类型是列表:list。list是一种有序的集合,可以随时添加和删除其中的元素。
- 具有顺序的一组对象
- 可以随意访问其中的任意位置
- 可以添加和删除
- 其中的元素不需要是同类型,但最好是一组同质对象
import sys
# shoplist = ['apple', 'mango','carrot', 'banana']
shoplist = list()
shoplist.append('apple')
shoplist.append('mango')
shoplist.append('carrot')
shoplist.append('banana')
print('shoplist len is {}'.format(len(shoplist)))
sys.stdout.write('These items are:')
for item in shoplist:
sys.stdout.write(str(item) + '')
print('\nI also want to buy rice.')
shoplist.append('rice')
print('New shoplist is : {}'.format(shoplist))
shoplist.sort()
print('Sorted list is {}'.format(shoplist))
print('the first item is {}'.format(shoplist[0]))
-----------------------------------------------------
shoplist len is 4
These items are:applemangocarrotbanana
I also want to buy rice.
New shoplist is : ['apple', 'mango', 'carrot', 'banana', 'rice']
Sorted list is ['apple', 'banana', 'carrot', 'mango', 'rice']
the first item is apple
-
tuple
- 具有顺序的一组对象【同list】
- 可以随意访问其中的任意位置【同list】
- 不可以添加和删除
- 其中的元素不需要是同类型
tuple和list非常类似,但是tuple一旦初始化就不能修改,它也没有append(),insert()这样的方法。其他获取元素的方法和list是一样的,你可以正常地使用[0],[-1],但不能赋值成另外的元素。uple不可变,所以代码更安全。如果可能,能用tuple代替list就尽量用tuple。
定义一个只有1个元素的tuple
>>> t = (1,)
>>> t
(1,)
如果定义成这样:
>>> t = (1)
>>> t
1
定义的不是tuple,是1这个数!这是因为括号()既可以表示tuple,又可以表示数学公式中的小括号,这就产生了歧义,因此,Python规定,这种情况下,按小括号进行计算,计算结果自然是1。
Python在显示只有1个元素的tuple时,会加一个逗号,,以免你误解成数学计算意义上的括号。
- 操作序列对象
- 通过[]访问
- 通过[]设定值
- 通过for枚举
- 通过[:]访问
- 通过[:]设定值
- 通过[::]设定步进
zoo = ('python', 'elephant', 'penguin') # 用()来表示
print('number is {}'.format(len(zoo)))
new_zoo = 'monkey', 'camel', zoo #可以省略()
print ('new number is {}'.format(len(new_zoo)))
print('All animals in new zoo are {}'.format(new_zoo))
print('animals are from old zoo are {}'.format(new_zoo[2]))
print('Number of animals in new zoo is {}'.format(len(new_zoo)-1+len(new_zoo[2])))
-----------------------------------------------
number is 3
new number is 3
All animals in new zoo are ('monkey', 'camel', ('python', 'elephant', 'penguin'))
animals are from old zoo are ('python', 'elephant', 'penguin')
Number of animals in new zoo is 5
r = 1, 2, 3 #另一种写法
r
print(r)
a, b, c = r
print(a)
print(b)
print(c)
------------------------
(1, 2, 3)
1
2
3
def f():
return (1, 2, 3)
a, b, c = f()
print(a)
print(b)
print(c)
----------------------
1
2
3
print(a)
print(b)
a, b = b, a # 无中间变量翻转对象
print(a)
print(b)
-------------------------------
2
1
1
2
list和tuple是Python内置的有序集合,一个可变,一个不可变。根据需要来选择使用它们。
shoplist =['apple', 'banana', 'carrot', 'mango', 'rice']
print('0 is {}'.format(shoplist[0]))
print('1 is {}'.format(shoplist[1]))
print('2 is {}'.format(shoplist[2]))
print('3 is {}'.format(shoplist[3]))
print('4 is {}'.format(shoplist[4]))
print('-1 is {}'.format(shoplist[-1]))
print('-2 is {}'.format(shoplist[-2]))
print('-3 is {}'.format(shoplist[-3]))
print('-4 is {}'.format(shoplist[-4]))
print('-5 is {}'.format(shoplist[-5]))
print('0 to 3 is {}'.format(shoplist[0:3]))
print('1 to end is {}'.format(shoplist[1: ]))
print('2 to -1 is {}'.format(shoplist[2: -1]))
print('start to end is {}'.format(shoplist[:]))
---------------------------------------------------
0 is apple
1 is banana
2 is carrot
3 is mango
4 is rice
-1 is rice
-2 is mango
-3 is carrot
-4 is banana
-5 is apple
0 to 3 is ['apple', 'banana', 'carrot']
1 to end is ['banana', 'carrot', 'mango', 'rice']
2 to -1 is ['carrot', 'mango']
start to end is ['apple', 'banana', 'carrot', 'mango', 'rice']
dict
Python内置了字典:dict的支持,dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度。set
set和dict类似,也是一组key的集合,但不存储value。由于key不能重复,所以,在set中,没有重复的key。
- string
name = 'swaroop'
print('Character 0 is {}'.format(name[0]))
print('Character 1 to 3 is {}'.format(name[1: 3]))
print('Character 2 to end is {}'.format(name[2: ]))
print('Character 2 to -1 is {}'.format(name[ 2: -1]))
print('Character start to end is {}'.format(name[:]))
print('reversed characters is {}'.format(name[::-1]))
-----------------------------------------------------
Character 0 is s
Character 1 to 3 is wa
Character 2 to end is aroop
Character 2 to -1 is aroo
Character start to end is swaroop
reversed characters is pooraws
实战练习
#练习
# 1. 建立一个list, 内容为10以内所有的质数
primes = [2, 3, 5, 7]
# 2.计算出100内所有质数的列表
primes = [2, 3, 5, 7]
for i in range(10, 100):
prime = True
for j in primes:
if i % j ==0:
prime = False
break
if prime:
primes.append(i)
print(primes)
----------------------------
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
primes = []
l = list(range(2, 100))
while l:
j = l.pop(0)
primes.append(j)
i = 2
while j * i <= 100:
if j * i in l:
l.remove(j * i)
i += 1
print(primes)
# 3.将这个列表转为tuple
tuple(primes)
--------------
# 4.根据上面的tuple, 获得反转的tuple
tuple(reversed(tuple(primes)))
# 5.将一个list分为两个: 第一个list拥有原本list前一半的反向, 第二个list拥有原本list后一半的反向
list(reversed(primes[:len(primes) //2])), list(reversed(primes[len(primes) // 2: ]))
-----------------------------------------------
([37, 31, 29, 23, 19, 17, 13, 11, 7, 5, 3, 2],
[97, 89, 83, 79, 73, 71, 67, 61, 59, 53, 47, 43, 41])
primes[len(primes) // 2:: -1 ], primes[:len(primes) //2 : -1]
--------------------------------------
([41, 37, 31, 29, 23, 19, 17, 13, 11, 7, 5, 3, 2],
[97, 89, 83, 79, 73, 71, 67, 61, 59, 53, 47, 43])