python 中数据类型总结--str, list, tuple, dict, set

Posted on 2020-07-14 21:17  青柠2020  阅读(473)  评论(0)    收藏  举报
python 中数据类型总结
1, 字符串/string, str  (单,双引号)
1) 定义:字符串(String),是由零个或多个字符组成的有限串行。一般记为s=a[1]a[2]...a[n]。
 用一对单/双引号括起来的内容。
str1 = "12345"
str2 = 'Chery'
str3 = "Automobile"
str4 = '["a",  "b",  "c", ]'
str5 = ' This is a new book.'
2)操作:
2.1) 字符串连接(+)
>>> str1 = "12345"
>>> str2 = 'Chery'
>>> str3 = "Automobile"
>>> str4 = '["a",  "b",  "c", ]'
>>> str5 = ' This is a new book.'
>>> str2+str3
'CheryAutomobile'
>>>
2.2) 统计字符串的长度(len(s))
>>> len(str5)
20
>>>
2.3)  切片读取
>>> str3[:]
'Automobile'
>>> str3[3:]
'omobile'
>>> str[0:]
>>> str3[0:]
'Automobile'
>>> str3[0:-1]
'Automobil'
>>> str3[-2]
'l'
>>> str3[1:8]
'utomobi'
>>>
2.4) 去除两边,左,右侧的空格(strip(), lstrip(),rstrip())
>>> str6 = "   Book   "
>>> str6.strip()
'Book'
>>> str6  ##   s.strip() 不影响原s的值  ##
'   Book   '
>>> str6.lstrip()
'Book   '
>>> str6.rstrip()
'   Book'
>>>
2.5) 字符串复制(*)
>>> str2 = 'Chery'
>>> str2*3
'CheryCheryChery'
>>>
2.6 )大小写转化(s.upper, s.lower)
>>> str2 = 'Chery'
>>> str2.upper()
'CHERY'
>>> str2  ##   s.upper() 不影响原s的值  ##
'Chery'
>>>
>>> str3 = "Automobile"
>>> str3.lower()
'automobile'
>>>
2.7) 成员运算(in, not in)
>>> str3 = "Automobile"
>>> 'n' in str3
False
>>> 'm' in str3
True
>>> 'f' not in str3
True
>>>
2.8) 编码和解码(encode, decode)
>>> s = "青青子吟,悠悠我心"
>>> a_end = s.encode(encoding = 'utf-8', errors = 'strict')
>>> a_end
b'\xe9\x9d\x92\xe9\x9d\x92\xe5\xad\x90\xe5\x90\x9f\xef\xbc\x8c\xe6\x82\xa0\xe6\x82\xa0\xe6\x88\x91\xe5\xbf\x83'
>>> >>> a_end.decode(encoding = 'utf-8', errors='strict')
'青青子吟,悠悠我心'
>>>
2.9) 字符串分割为列表(string.split(str='', num = string.count(str))
分隔符不写时,默认空格为分隔符
>>> str5 = ' This is a new book.'
>>> ls5 = str5.split()
>>> ls5
['This', 'is', 'a', 'new', 'book.']
>>>
>>> str6 = ' This is, a new, book.'
>>> str6.split(',')
[' This is', ' a new', ' book.']
>>>
>>> list0 = ['apple',  'Banana', 'Eat', ]
>>> ''.join(list0)
'appleBananaEat'
2.10) 字符串中替换(string.replace(str1,str2))  用str2替换string中的str1
>>> str2 = 'Chery'
>>> str2.replace('h', 'k')
'Ckery'
>>>
2.11) 字符串的循环遍历
>>> str2 = 'Chery'
>>> for j in str2:
 print(j)
 
C
h
e
r
y
>>>
2. 逻辑运算符的优先级顺序
not > and > or
3. 列表  (中括号[ ])
1)定义
la = []
lb = ['1', 'abc', "hello"]
lc = ['xyz', 'cctv',  ]
2)对列表的操作:
2.1)追加元素(list.append(x),等效于 a[len(a)]:[x])
>>> lc = ['xyz', 'cctv',  ]
>>> lc.append('ahtv')    ## 方法对对象的修改,返回None,不产生新的对象; append对象是字符串##
>>> lc
['xyz', 'cctv', 'ahtv']
>>> lc[len(lc):] = ['ahtv']
>>> lc
['xyz', 'cctv', 'ahtv',  'ahtv']
>>>    
2.2) 合并列表 list.extend(L) 等效于 a[len(a):] = L  ## extend 对象是列表##
>>> lb = ['1', 'abc', "hello"]
>>> lc = ['xyz', 'cctv',  ]
>>> lb.extend(lc)  ## 方法对对象的修改,返回None,不产生新的对象##
>>> lb
['1', 'abc', 'hello', 'xyz', 'cctv']
>>> lb[len(lb):]=lc
>>> lb
['1', 'abc', 'hello', 'xyz', 'cctv', 'xyz', 'cctv']
>>>
如果字符串被extend到列表,则字符串会被拆分为单个字符追加到列表中
>>> lc = ['xyz', 'cctv',  ]
>>> lc.extend('love')
>>> lc
['xyz', 'cctv', 'l', 'o', 'v', 'e']
>>>
2.3) 统计元素个数( list.count(x))
>>> lm=['h', 'e', 'l', 'l', 'o', 'a', 'p', 'p', 'l', 'e']
>>> lm.count('l')
3
>>>
2.4) 列表切片(同str)
>>> lm=['h', 'e', 'l', 'l', 'o', 'a', 'p', 'p', 'l', 'e']
>>> lm[2:5]
['l', 'l', 'o']
>>>
2.5 ) 插入元素: list.insert(i,x)
>>> lc = ['xyz', 'cctv', 'l', 'o', 'v', 'e']
>>> lc.insert(2,'VOA')
>>> lc
['xyz', 'cctv', 'VOA', 'l', 'o', 'v', 'e']
>>>
2.6) 删除元素: list.remove(x),  list.pop([i]),  del list[i]
>>> lc = ['xyz', 'cctv', 'l', 'o', 'v', 'e']
>>> del lc[-1]
>>> lc
['xyz', 'cctv', 'l', 'o', 'v']
>>> del lc[-2]
>>> lc
['xyz', 'cctv', 'l', 'v']
>>> lc.remove('l')
>>> lc
['xyz', 'cctv', 'v']
>>> lc.remove('v')
>>> lc
['xyz', 'cctv']
>>> lc.pop(1) ## pop([i])后,会返回删除的元素###
'cctv'
>>> lc
['xyz']
>>>
2.7) 列表排序  ( list.sort(False = True),  sorted(iterabel, reverse = True, 被排列的对象需一致,同为str或 int)
>>> lm = [ 1,2, 6, -9, 11, -22, 4, ]
>>> lm.sort()
>>> lm
[-22, -9, 1, 2, 4, 6, 11]    ##默认升序排列###
>>>
>>> lr = [ 'a', 's', 'g']
>>> lr.sort()
>>> lr
['a', 'g', 's']
>>>
>>> ln = [ 1,2, 6, -9, 11, -22, 4, ]
>>> b = sorted(ln, reverse = True)    ##改名默认升序排列###
>>> ln    ##用sorted函数时,对原数列没影响,产生了新数列##
[1, 2, 6, -9, 11, -22, 4]
>>> b
[11, 6, 4, 2, 1, -9, -22]
>>>
2.8 ) list 和str之间的转化  (  list(string)--强制转化,  s.split([sep [, max split]) -函数转化)
>>> string = "hello, this is my friend"
>>> list_string = list(string)
>>> list_string  ##直接对字符串转化为list时,会把每个字符拆分为列表元素##
['h', 'e', 'l', 'l', 'o', ',', ' ', 't', 'h', 'i', 's', ' ', 'i', 's', ' ', 'm', 'y', ' ', 'f', 'r', 'i', 'e', 'n', 'd']
>>>
>>> string2 = "hello, this is my friend"
>>> string2.split()   ##split后,对原字符串无影响###
['hello,', 'this', 'is', 'my', 'friend']
>>> string2
'hello, this is my friend'
>>> type(string2)
<class 'str'>
>>>
>>> a_list = ['hello,', 'this', 'is', 'my', 'friend']
>>> "".join(a_list)
'hello,thisismyfriend'
>>> ", ".join(a_list)
'hello,, this, is, my, friend'
>>>
2.9)  求列表的长度 len(list)
>>> str_b = ['hello,', 'this', 'is', 'my', 'friend']
>>> len(str_b)
5
>>>
2.10) 列表连接(同字符串  + 号连接)
>>> list_b = ['hello,', 'this', 'is', 'my', 'friend']
>>> list_c = [124, '789']
>>> list_b+list_c
['hello,', 'this', 'is', 'my', 'friend', 124, '789']
>>>
2.11) 成员运算 ( in, not in)
>>> list_m = ['hello,', 'this', 'is', 'my', 'friend', 124, '789']
>>> 'is' in list_m
True
>>> 'class' in list_m
False
>>>
2.12) 列表遍历  (  for in )
>>> list_m = ['hello,', 'this', 'is', 'my', 'friend', 124, '789']
>>> for i in list_m:
 print(i, end='')
 
hello,thisismyfriend124789
>>>
2.13) enumerate(list) 函数,返回 列表元素索引序号和元素
>>> seasons = ['spring', 'summer', 'fall', 'winter', ]
>>> list(enumerate(seasons))
[(0, 'spring'), (1, 'summer'), (2, 'fall'), (3, 'winter')]
>>>
2.13)列表解析式
[expr for iter_val in iterable],  expr 为表达式, iter_val 为序列变量, iterable 为列表
>>> la = [n for n in range(30) if n%7 ==0 ]
>>> la
[0, 7, 14, 21, 28]
>>>
>>> foo = lambda x : x*x
>>> lb = [ foo(i) for i in range(7)]
>>> lb
[0, 1, 4, 9, 16, 25, 36]
>>>
>>> seasons = ['spring', 'summer', 'fall', 'winter', ]
>>> foo2 = lambda i, ses : "%d : %s" %(i, ses)
>>> [foo2(i,ses) for i, ses in enumerate(seasons)]
['0 : spring', '1 : summer', '2 : fall', '3 : winter']
>>>
4,字典,(花括号,{ })
  4.1) 字典定义,方法一:
  mydic = {}  定义空字典
   字典数据结构 key:value
  person = {'name':"Lucas", "sex":'male', "age":22}
       增加键值对
  person["money"] = 880
       方法二, 用元组转化(元组中每个元素为列表或元组,且列表中有且只有2个元素,分别转化为key和value)
       >>> names = (["Linda",  "Female"],  ["James", "Male"])
  >>> name = dict(names)
  >>> name
  {'Linda': 'Female', 'James': 'Male'}
  >>>
  >>> names2 = (("Linda",  "Female"),  ("James", "Male"))
  >>> name2 = dict(names2)
  >>> name2
  {'Linda': 'Female', 'James': 'Male'}
  >>>
 4.2)字典访问: 字典名['key']
      >>> name2['Linda']
  'Female'
  >>>
 4.3) 字典遍历  for  in  
  names2 = {'Linda': 'Female', 'James': 'Male'}    
  >>> for key in  name2:
 
       print(key)
    Linda
    James
  >>>
     4.4) 字典元素删除:d.pop(key),  或者 del  d[key]
  1) d.pop(key)  返回被删除的value
  >>> name2= {'Linda': 'Female', 'James': 'Male'}
  >>> name2.pop('Linda')
  'Female'
  >>> name2
  {'James': 'Male'}
  >>>
  2) del name2[key]  无返回
  >>> name2={'James': 'Male'}
  >>> del name2['James']
  >>> name2
  {}
  >>>
  4.5) 获取字典的值:  d.keys(), 获取字典key并返回列表;d.get(key)---返回key的值; 
    d.values(), 返回值 返回列表;   d.items() 以元组形式返回
  >>> names = {'Linda': 'Female', 'James': 'Male' ,  'Lucas':'Male'}
  >>> ky = names.keys()
  >>> ky
  dict_keys(['Linda', 'James', 'Lucas'])
  >>> type(ky)
  <class 'dict_keys'>
  >>>
  
  >>> names.values()
  dict_values(['Female', 'Male', 'Male'])
  >>>
 
  >>> names.items()
  dict_items([('Linda', 'Female'), ('James', 'Male'), ('Lucas', 'Male')])
  >>>
  
  >>> names.get('Linda')
  'Female'
  >>>
5, 元组,小括号( ( ))
  定义:  tp = ()
  当不同类型元素给变量赋值时,将被转化为元组
  >>> tp2 = 1, 'abc',  "元素"
  >>> tp2
  (1, 'abc', '元素')
  >>>
  元组的元素不能被修改,可以像字符串那样切片,遍历
 
  >>> tp2 = (1, 'abc', '元素')
  >>> tp2[0]
  1
  >>> tp2[2]
  '元素'
  >>> tp2[0:2]
  (1, 'abc')
  >>> for i in tp2:
   print (i)
 
  1
  abc
  元素
  >>>
  list 和 tuple之间转化
  >>> tp3 = (1, 'abc', '元素',  '798')
  >>> list(tp3)
  [1, 'abc', '元素', '798']
  >>> list_a = [123, 'cctv', ('a','b'), '7788']
  >>> tuple(list_a)
  (123, 'cctv', ('a', 'b'), '7788')
  >>>
6, 集合 set, 用花括号表示和字典一样
  所有在定义空集合时不能用s={},这会被python解释为字典类型。  
  定义一个空集合:   
  >>> s = set()
  >>> type(s)
  <class 'set'>
  >>>
  6.1)集合中的元素不能重复, 故当一个字符串赋值给集合时,
    字符串中各字符会被拆分不重复的存入到集合中。
  >>> s1 = "this is a new book"
  >>> s2 = set(s1)
  >>> s2
  {'h', 'i', 'w', 'b', 'e', 'o', ' ', 's', 'n', 't', 'k', 'a'}
  >>>
  6.2) 集合中增加元素  set.add(item)
  >>> s2.add('hello')
  >>> s2
  {'h', 'i', 'w', 'hello', 'b', 'e', 'o', ' ', 's', 'n', 't', 'k', 'a'}
  >>>
  set 中的元素是无序的, 虽然可以遍历,但每次遍历的结果可能不一致
  s2={'h', 'i', 'w', 'hello', 'b', 'e', 'o', ' ', 's', 'n', 't', 'k', 'a'}
  for i in s2:
      print(i, end = ',')
  下面是两次运行的结果:
  e,k,a,b,o,n, ,s,hello,w,h,t,i,
  h, ,w,o,n,a,k,s,i,b,hello,e,t,
  6.3) 集合中删除元素:set.pop() 随机删除一个set中的元素并返回值;
              set.remove(obj), obj必须是set中的元素,否则报错;
              set.discard(obj), obj若是set中的元素,直接删除;若不在,do nothing
              set.clear(), 清空set中的元素
 
    >>> seta= {'o', 't', 'e', 'k', 'w', 'hello', 'a', 'h', 's', 'n'}
    >>> seta.pop()
    'o'
    >>> seta.pop()
    't'
    >>> seta.remove('w')
    >>> seta.remove('a')
    >>> seta.discard('m')
    >>> seta.discard('s')
    >>> seta
    {'e', 'k', 'hello', 'h', 'n'}
    >>> seta.clear()
    >>> seta
    set()
    >>>
 
  
  
  
  
 
    

博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3