简单数据类型:整型,浮点型和布尔型。
容器数据类型:列表,元组,字典,集合和字符串。
列表是有序集合,无固定大小,能够保存任意数量任意类型的Python对象。
中括号[]
和逗号,
x = ['Monday','Tuesday','Wednesday','Thursday','Friday'] print(x,type(x))
['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'] <class 'list'>
x = list(range(10)) print(x,type(x))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] <class 'list'>
x = [0]*5 print(x,type(x))
[0, 0, 0, 0, 0] <class 'list'>
x = [0 for i in range(5)] print(x,type(x))
[0, 0, 0, 0, 0] <class 'list'>
x = [i for i in range(1,10,2)] print(x,type(x))
[1, 3, 5, 7, 9] <class 'list'>
x = [i for i in range(100) if (i%2)!=0 and (i%3)==0] print(x,type(x))
[3, 9, 15, 21, 27, 33, 39, 45, 51, 57, 63, 69, 75, 81, 87, 93, 99] <class 'list'>
注:
[1,2,3]
,也有三个整数对象。x = [a] * 4
中,如果a
发生了改变,x
中4个a
也会随之改变。举例:
x = [[0]*3]*4 print(x,type(x))
[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]] <class 'list'>
x[0][0] = 1 print(x,type(x))
[[1, 0, 0], [1, 0, 0], [1, 0, 0], [1, 0, 0]] <class 'list'>
a = [0] * 3 x = [a] * 4 print(x,type(x))
[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]] <class 'list'>
x[0][0] = 1 print(x,type(x))
[[1, 0, 0], [1, 0, 0], [1, 0, 0], [1, 0, 0]] <class 'list'>
mix = [1,'lsgo',3.14,[1,2,3]] print(mix,type(mix))
[1, 'lsgo', 3.14, [1, 2, 3]] <class 'list'>
empty = [] print(empty,type(empty))
[] <class 'list'>
由于列表的元素可以随意更改,所以附加(append
,extend
)、插入(insert
)、删除(remove
,pop
)这些操作列表都可以使用
x = ['Monday','Tuesday','Webnesday','Thursday','Friday'] x.append('Thursday') print(x)
['Monday', 'Tuesday', 'Webnesday', 'Thursday', 'Friday', 'Thursday']
append()
和extend()
的区别x = ['Monday','Tuesday','Webnesday'] x.append(['Thursday','Sunday']) print(x)
['Monday', 'Tuesday', 'Webnesday', ['Thursday', 'Sunday']]
x = ['Monday','Tuesday','Webnesday'] x.extend(['Thursday','Sunday']) print(x)
['Monday', 'Tuesday', 'Webnesday', 'Thursday', 'Sunday']
x = ['Monday','Tuesday','Webnesday','Thursday','Friday'] x.insert(2,'Sunday') print(x)
['Monday', 'Tuesday', 'Sunday', 'Webnesday', 'Thursday', 'Friday']
x = ['Monday','Tuesday','Webnesday','Thursday','Friday'] x.remove('Monday') print(x)
['Tuesday', 'Webnesday', 'Thursday', 'Friday']
x = ['Monday','Tuesday','Webnesday','Thursday','Friday'] y = x.pop() print(y)
Friday
知道要删除元素在列表中的位置,可以使用del
x = ['Monday','Tuesday','Wednesday','Thursday','Friday'] del x[0:2] print(x)
['Wednesday', 'Thursday', 'Friday']
x = ['Monday','Tuesday','Wednesday'] print(x[0],x[-1])
Monday Wednesday
切片的通用写法 start:stop:step
x = ['Monday','Tuesday','Wednesday','Thursday','Friday'] print(x[3:]) print(x[:3]) print(x[1:3]) print(x[1:-1:2])
['Thursday', 'Friday'] ['Monday', 'Tuesday', 'Wednesday'] ['Tuesday', 'Wednesday'] ['Tuesday', 'Thursday']
列表拼接有两种方式,用+
和*
,前者首尾拼接,后者复制拼接
list1 = [123,456] list2 = [456,123] list3 = [123,456] print(list1 == list2) print(list1 == list3) list4 = list1+list2 print(list4) list5 = list3*3 print(list5) print(123 in list3) print(456 not in list3)
False True [123, 456, 456, 123] [123, 456, 123, 456, 123, 456] True False
list.count(obj)
统计某个元素在列表中出现的次数list1 = [123,456]*3 print(list1) num = list1.count(123) print(num)
[123, 456, 123, 456, 123, 456] 3
list.index(x,start,end)
从列表中找出某个值第一个匹配项的索引位置list1 = [123,456] * 5 print(list1.index(123)) print(list1.index(123,1)) print(list1.index(123,3,7))
0 2 4
list.reverse()
反向列表中的元素x = [123,456,789] x.reverse() print(x)
[789, 456, 123]
list.sort(key = None,reverse = False)
对原列表进行排序x = [123,456,789,213] x.sort() print(x) x.sort(reverse=True) print(x)
t1 = (1,10.31,'python') t2 = 1,10.31,'python' print(t1,type(t1)) print(t2,type(t2)) tup = (1,2,3,4,5,6,7,8) print(tup[1]) print(tup[5:]) print(tup[:5]) tup1 = tup print(tup1)
(1, 10.31, 'python') <class 'tuple'> (1, 10.31, 'python') <class 'tuple'> 2 (6, 7, 8) (1, 2, 3, 4, 5) (1, 2, 3, 4, 5, 6, 7, 8)
week = ('Monday','Tuesday','Thursday','Friday') week = week[:2] + ('Wednesday',) + week[2:] print(week)
('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday')
t1 = (123,456) t2 = (456,123) t3 = (123,456) print(t1 == t2) print(t1 == t3) t4 = t1 + t2 print(t4)
t = (1,10.31,'python') print(t.count('python')) print(t.index(10.31))
1 1
#解压一维元组 t = (1,10.31,'python') (a,b,c) = t print(a,b,c) #解压二维元组 t = (1,10.31,('OK','python')) (a,b,(c,d)) = t print(a,b,c,d) #通配符提取你想要的变量 t = 1,2,3,4,5 a,b,*rest,c = t print(a,b,c) print(rest) #不需要变量名就用*加上下划线代替 t = 1,2,3,4,5 a,b,*_ = t print(a,b)
1 10.31 python 1 10.31 OK python 1 2 5 [3, 4] 1 2
t1 = 'i love Python' print(t1,type(t1))
i love Python <class 'str'>
print('let\'s go') print("let's go") print('C:\\now') print('C:\\Program Files\\Intel\\Wifi\\Help')
let's go let's go C:\now C:\Program Files\Intel\Wifi\Help
print(r'C:\Program Files\Intel\Wifi\Help')
C:\Program Files\Intel\Wifi\Help
str1 = 'I love LsgoGroup' print(str1[:6]) print(str1[5]) print(str1[:6]+'插入的字符串'+str1[6:])
I love e I love插入的字符串 LsgoGroup
str2 = 'xiaoxie' print(str2.capitalize())
Xiaoxie
str2 = 'DAXIExiaoxie' print(str2.lower()) print(str2.upper()) print(str2.swapcase())
daxiexiaoxie DAXIEXIAOXIE daxieXIAOXIE
str2 = 'DAXIExiaoxie' print(str2.count('xi'))
2
str2 = 'DAXIExiaoxie' print(str2.find('xi')) print(str2.find('ix')) print(str2.rfind('xi'))
5 -1 9
str3 = '12345' print(str3.isnumeric()) str3 += 'a' print(str3.isnumeric())
True False
str4 = '1101' print(str4.ljust(8,'0')) print(str4.rjust(8,'0'))
11010000 00001101
str5 = ' I love LsgoGroup ' print(str5.lstrip()) print(str5.lstrip().strip('I')) print(str5.rstrip()) print(str5.strip()) print(str5.strip().strip('p'))
I love LsgoGroup love LsgoGroup I love LsgoGroup I love LsgoGroup I love LsgoGrou
str5 = 'I Love LsgoGroup' print(str5.strip().partition('o')) print(str5.strip().partition('m'))
('I L', 'o', 've LsgoGroup') ('I Love LsgoGroup', '', '')
str5 = 'I Love LsgoGroup' print(str5.strip().replace('I','We'))
We Love LsgoGroup
str5 = 'I Love LsgoGroup' print(str5.strip().split()) print(str5.strip().split('p'))
['I', 'Love', 'LsgoGroup'] ['I Love LsgoGrou', '']
str6 = 'I \n Love \n LsgoGroup' print(str6.splitlines()) print(str6.splitlines(True))
['I ', ' Love ', ' LsgoGroup'] ['I \n', ' Love \n', ' LsgoGroup']
str7 = 'this is string example...wow!!!' intab = 'aeiou' outtab = '12345' trantab = str7.maketrans(intab,outtab) print(trantab) print(str7.translate(trantab))
{97: 49, 101: 50, 105: 51, 111: 52, 117: 53} th3s 3s str3ng 2x1mpl2...w4w!!!
str8 = "{0} Love {1}".format('I','Lsgogroup') #位置参数 print(str8) str8 = "{a} Love {b}".format(a = 'I',b = 'Lsgogroup') #关键字参数 print(str8) str8 = "{0} Love {b}".format('I',b = 'Lsgogroup') #位置参数要在关键字参数之前 print(str8) str8 = '{0:.2f}{1}'.format(27.658,'GB')#保留小数点后两位 print(str8)
I Love Lsgogroup I Love Lsgogroup I Love Lsgogroup 27.66GB
判断数据类型X
是否为可变类型的方法:
i = 1 print(id(i)) i += 2 print(id(i)) l = [1,2] print(id(l)) l.append('Python') print(id(l))
140726725256992 140726725257056 2553863469376 2553863469376
print(hash({1,2,3}))
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-26-653299afdf87> in <module> ----> 1 print(hash({1,2,3})) TypeError: unhashable type: 'set'
brand = ['李宁','Nike','Adidas'] slogan = ['一切皆有可能','Just do it','Impossible is nothing'] print('Nike 的口号是:',slogan[brand.index('Nike')]) dic = {'李宁':'一切皆有可能','Nike':'Just do it','Adidas':'Impossible is nothing'} print('Nike 的口号是:',dic['Nike'])
Nike 的口号是: Just do it Nike 的口号是: Just do it
dic1 = dict([('apple',4139),('peach',4127),('cherry',4098)]) dic2 = dict((('apple',4139),('peach',4127),('cherry',4098))) print(dic1) print(dic2)
{'apple': 4139, 'peach': 4127, 'cherry': 4098} {'apple': 4139, 'peach': 4127, 'cherry': 4098}
seq = ('name','age','sex') dic1 = dict.fromkeys(seq) print(dic1) dic2 = dict.fromkeys(seq,10) print(dic2) dic3 = dict.fromkeys(seq,('小马','8','男')) print(dic3)
{'name': None, 'age': None, 'sex': None} {'name': 10, 'age': 10, 'sex': 10} {'name': ('小马', '8', '男'), 'age': ('小马', '8', '男'), 'sex': ('小马', '8', '男')}
dic = {'Sex':'female','Age':7,'Name':'Zara'} print(dic.values()) print(list(dic.values()))
dict_values(['female', 7, 'Zara']) ['female', 7, 'Zara']
dic = {'Name':'Lsgogroup','Age':7} print(dic.items()) print(tuple(dic.items())) print(list(dic.items()))
dict_items([('Name', 'Lsgogroup'), ('Age', 7)]) (('Name', 'Lsgogroup'), ('Age', 7)) [('Name', 'Lsgogroup'), ('Age', 7)]
dic = {'Name':'Lsgogroup','Age':27} print('Age 值为:%s'% dic.get('Age')) print('Sex 值为:%s'% dic.get('Sex','NA')) print(dic)
Age 值为:27 Sex 值为:NA {'Name': 'Lsgogroup', 'Age': 27}
dic = {'Name':'Lsgogroup','Age':7} print('Age 键的值为:%s' % dic.setdefault('Age',None)) print('Sex 键的值为:%s' % dic.setdefault('Sex',None)) print(dic)
Age 键的值为:7 Sex 键的值为:None {'Name': 'Lsgogroup', 'Age': 7, 'Sex': None}
dic1 = {1:'a',2:{1,2}} print(dic1.pop(1),dic1) print(dic1.pop(3,'nokey'),dic1) del dic1[2] print(dic1)
a {2: {1, 2}} nokey {2: {1, 2}} {}
dic1 = {1:'a',2:[1,2]} print(dic1.popitem()) print(dic1)
(2, [1, 2]) {1: 'a'}
dic = {'Name':'Zara','Age':7} print("字典长度:%d" % len(dic)) dic.clear() print("字典删除后的长度:%d" % len(dic))
字典长度:2 字典删除后的长度:0
basket = set() basket.add('apple') basket.add('banana') print(basket)
{'banana', 'apple'}
集合会自动过滤重复元素
使用set()函数将列表或元组转换成集合
a = set('abracadabra') print(a) b = set(('Google','Lsgogroup','Taobao','Taobao')) print(b)
{'a', 'r', 'b', 'c', 'd'} {'Google', 'Lsgogroup', 'Taobao'}
s = set(['Google','Baidu','Taobao']) for item in s: print(item)
Google Baidu Taobao
fruits = {'apple','banana','cherry'} fruits.add('orange') print(fruits) fruits.add('apple') print(fruits)
{'banana', 'cherry', 'orange', 'apple'} {'banana', 'cherry', 'orange', 'apple'}
x = {'apple','banana','cherry'} y = {'google','baidu','apple'} x.update(y) print(x) y.update(['lsgo','dreamtech']) print(y)
{'banana', 'apple', 'baidu', 'cherry', 'google'} {'apple', 'baidu', 'google', 'dreamtech', 'lsgo'}
fruits = {'apple','banana','cherry'} fruits.remove('banana') print(fruits)
{'cherry', 'apple'}
fruits = {'apple','banana','cherry'} fruits.discard('banana') print(fruits)
{'cherry', 'apple'}
fruits = {'apple','banana','cherry'} x = fruits.pop() print(fruits) print(x)
{'cherry', 'apple'} banana
#set.intersection(set1,set2)返回两个集合的交集 #set1 & set2 返回两个集合的交集 #set.intersection_update(set1,set2)交集,在原始的集合上移除不重叠的元素 a = set('abracadabra') b = set('alacazam') print(a) print(b) c = a.intersection(b) print(c) print(a&b) print(a) a.intersection_update(b) print(a) print('*'*80) #set.union(set1,set2)返回两个集合的并集 #set1 | set2 返回两个集合的并集 a = set('abracadabra') b = set('alacazam') print(a) print(b) print(a | b) print(a.union(b)) print('*'*80) #set.difference(set)返回集合的差集 #set1 - set2 返回集合的差集 #set.difference_update(set)集合的差集,直接在原集合中移除元素,没有返回值 a = set('abracadabra') b = set('alacazam') print(a) print(b) c = a.difference(b) print(c) print(a-b) print(a) a.difference_update(b) print(a) print('*'*80) #set.symmetric_difference(set)返回集合的异或。 #set1 ^ set2 返回集合的异或 #set.symmetric_difference_update(set)移除当前集合中在另外一个指定集合相同的元素,并将另外一个指定集合中不同的元素插入到当前集合中。 a = set('abracadabra') b = set('alacazam') print(a) # {'r', 'a', 'c', 'b', 'd'} print(b) # {'c', 'a', 'l', 'm', 'z'} c = a.symmetric_difference(b) print(c) # {'m', 'r', 'l', 'b', 'z', 'd'} print(a ^ b) # {'m', 'r', 'l', 'b', 'z', 'd'} print(a) # {'r', 'd', 'c', 'a', 'b'} a.symmetric_difference_update(b) print(a) # {'r', 'b', 'm', 'l', 'z', 'd'}
{'a', 'r', 'b', 'c', 'd'} {'a', 'm', 'z', 'l', 'c'} {'a', 'c'} {'a', 'c'} {'a', 'r', 'b', 'c', 'd'} {'a', 'c'} ******************************************************************************** {'a', 'r', 'b', 'c', 'd'} {'a', 'm', 'z', 'l', 'c'} {'a', 'm', 'z', 'l', 'r', 'b', 'c', 'd'} {'a', 'm', 'z', 'l', 'r', 'b', 'c', 'd'} ******************************************************************************** {'a', 'r', 'b', 'c', 'd'} {'a', 'm', 'z', 'l', 'c'} {'d', 'r', 'b'} {'d', 'r', 'b'} {'a', 'r', 'b', 'c', 'd'} {'r', 'b', 'd'} ******************************************************************************** {'a', 'r', 'b', 'c', 'd'} {'a', 'm', 'z', 'l', 'c'} {'m', 'z', 'l', 'd', 'r', 'b'} {'m', 'z', 'l', 'd', 'r', 'b'} {'a', 'r', 'b', 'c', 'd'} {'m', 'z', 'l', 'r', 'b', 'd'}
se = set(range(4)) li = list(se) tu = tuple(se) print(se,type(se)) print(li,type(li)) print(tu,type(tu))
{0, 1, 2, 3} <class 'set'> [0, 1, 2, 3] <class 'list'> (0, 1, 2, 3) <class 'tuple'>
s = 'lsgogroup' x = reversed(s) print(type(x)) # <class 'reversed'> print(x) # <reversed object at 0x000002507E8EC2C8> print(list(x)) # ['p', 'u', 'o', 'r', 'g', 'o', 'g', 's', 'l'] t = ('l', 's', 'g', 'o', 'g', 'r', 'o', 'u', 'p') print(list(reversed(t))) # ['p', 'u', 'o', 'r', 'g', 'o', 'g', 's', 'l'] r = range(5, 9) print(list(reversed(r))) # [8, 7, 6, 5] x = [-8, 99, 3, 7, 83] print(list(reversed(x))) # [83, 7, 3, 99, -8]
<class 'reversed'> <reversed object at 0x000002529EC08880> ['p', 'u', 'o', 'r', 'g', 'o', 'g', 's', 'l'] ['p', 'u', 'o', 'r', 'g', 'o', 'g', 's', 'l'] [8, 7, 6, 5] [83, 7, 3, 99, -8]
seasons = ['Spring','Summer','Fall','Winter'] a = list(enumerate(seasons)) print(a) b = list(enumerate(seasons,1)) print(b) for i,element in a: print('{0},{1}'.format(i,element))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')] [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')] 0,Spring 1,Summer 2,Fall 3,Winter
a = [1,2,3] b = [4,5,6] c = [4,5,6,7,8] zippd = zip(a,b) print(zippd) print(list(zippd)) zippd = zip(a,c) print(list(zippd)) a1,a2 = zip(*zip(a,b)) print(list(a1)) print(list(a2))
<zip object at 0x000002529E144880> [(1, 4), (2, 5), (3, 6)] [(1, 4), (2, 5), (3, 6)] [1, 2, 3] [4, 5, 6]