列表
创建列表:
li = [1, 12, 9, "age", ["石振文", ["19", 10], "庞麦郎"], "alex", True] # 通过list类创建的对象,li
列表可包含int str list list_in_list bool
列表元素,可以被修改 li[1] = 120 或切片修改 li[0:1] = [120,11]
嵌套取值 li[4][2][1] = 10
基本操作,列表类中提供的方法:
- 索引 print(li[3])
- 切片 print(li[3:-1])
- 追加 li.appent("David")
- 删除 del li[2:6]
-
pop删除某个值(1.指定索引;2. 默认最后一个),并获取删除的值 # li = [11, 22, 33, 22, 44] # v = li.pop() # print(li) # print(v) # li = [11, 22, 33, 22, 44] # v = li.pop(1) # print(li) # print(v) remove 删除列表中的指定值,左边优先 # li = [11, 22, 33, 22, 44] # li.remove(22) # print(li) # PS: pop remove del li[0] del li[7:9] clear
- 长度 len()
- 循环 for item in li: while..
- 包含
- 清空 li.clear()
- 拷贝 li.copy()
- 计算元素出现次数 li.count("1")
- 插入 在指定索引位置插入元素 li.insert(2,"99")
- 扩展 li.extend([1,1,2,3])
# li = [11, 22, 33, 22, 44] # li.append([9898,"不得了"]) # [11, 22, 33, 22, 44, [9898, '不得了']] # 扩展原列表,参数:可迭代对象 # li.extend([9898,"不得了"]) # for i in [9898,"不得了"]: # li.append(i) # [11, 22, 33, 22, 44, 9898, '不得了'] # # li.extend("不得了") # print(li)
- 翻转 reverse()
- 排序 sort()
-
# 将当前列表进行翻转 # li = [11, 22, 33, 22, 44] # li.reverse() # print(li) # 列表的排序 # li = [11,44, 22, 33, 22] # li.sort() # li.sort(reverse=True) # print(li) ### 欠 # cmp # key # sorted
class list(object): """ list() -> new empty list list(iterable) -> new list initialized from iterable's items """ def append(self, p_object): # real signature unknown; restored from __doc__ """ L.append(object) -- append object to end """ pass def count(self, value): # real signature unknown; restored from __doc__ """ L.count(value) -> integer -- return number of occurrences of value """ return 0 def extend(self, iterable): # real signature unknown; restored from __doc__ """ L.extend(iterable) -- extend list by appending elements from the iterable """ pass def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__ """ L.index(value, [start, [stop]]) -> integer -- return first index of value. Raises ValueError if the value is not present. """ return 0 def insert(self, index, p_object): # real signature unknown; restored from __doc__ """ L.insert(index, object) -- insert object before index """ pass def pop(self, index=None): # real signature unknown; restored from __doc__ """ L.pop([index]) -> item -- remove and return item at index (default last). Raises IndexError if list is empty or index is out of range. """ pass def remove(self, value): # real signature unknown; restored from __doc__ """ L.remove(value) -- remove first occurrence of value. Raises ValueError if the value is not present. """ pass def reverse(self): # real signature unknown; restored from __doc__ """ L.reverse() -- reverse *IN PLACE* """ pass def sort(self, cmp=None, key=None, reverse=False): # real signature unknown; restored from __doc__ """ L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*; cmp(x, y) -> -1, 0, 1 """ pass def __add__(self, y): # real signature unknown; restored from __doc__ """ x.__add__(y) <==> x+y """ pass def __contains__(self, y): # real signature unknown; restored from __doc__ """ x.__contains__(y) <==> y in x """ pass def __delitem__(self, y): # real signature unknown; restored from __doc__ """ x.__delitem__(y) <==> del x[y] """ pass def __delslice__(self, i, j): # real signature unknown; restored from __doc__ """ x.__delslice__(i, j) <==> del x[i:j] Use of negative indices is not supported. """ pass def __eq__(self, y): # real signature unknown; restored from __doc__ """ x.__eq__(y) <==> x==y """ pass def __getattribute__(self, name): # real signature unknown; restored from __doc__ """ x.__getattribute__('name') <==> x.name """ pass def __getitem__(self, y): # real signature unknown; restored from __doc__ """ x.__getitem__(y) <==> x[y] """ pass def __getslice__(self, i, j): # real signature unknown; restored from __doc__ """ x.__getslice__(i, j) <==> x[i:j] Use of negative indices is not supported. """ pass def __ge__(self, y): # real signature unknown; restored from __doc__ """ x.__ge__(y) <==> x>=y """ pass def __gt__(self, y): # real signature unknown; restored from __doc__ """ x.__gt__(y) <==> x>y """ pass def __iadd__(self, y): # real signature unknown; restored from __doc__ """ x.__iadd__(y) <==> x+=y """ pass def __imul__(self, y): # real signature unknown; restored from __doc__ """ x.__imul__(y) <==> x*=y """ pass def __init__(self, seq=()): # known special case of list.__init__ """ list() -> new empty list list(iterable) -> new list initialized from iterable's items # (copied from class doc) """ pass def __iter__(self): # real signature unknown; restored from __doc__ """ x.__iter__() <==> iter(x) """ pass def __len__(self): # real signature unknown; restored from __doc__ """ x.__len__() <==> len(x) """ pass def __le__(self, y): # real signature unknown; restored from __doc__ """ x.__le__(y) <==> x<=y """ pass def __lt__(self, y): # real signature unknown; restored from __doc__ """ x.__lt__(y) <==> x<y """ pass def __mul__(self, n): # real signature unknown; restored from __doc__ """ x.__mul__(n) <==> x*n """ pass @staticmethod # known case of __new__ def __new__(S, *more): # real signature unknown; restored from __doc__ """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass def __ne__(self, y): # real signature unknown; restored from __doc__ """ x.__ne__(y) <==> x!=y """ pass def __repr__(self): # real signature unknown; restored from __doc__ """ x.__repr__() <==> repr(x) """ pass def __reversed__(self): # real signature unknown; restored from __doc__ """ L.__reversed__() -- return a reverse iterator over the list """ pass def __rmul__(self, n): # real signature unknown; restored from __doc__ """ x.__rmul__(n) <==> n*x """ pass def __setitem__(self, i, y): # real signature unknown; restored from __doc__ """ x.__setitem__(i, y) <==> x[i]=y """ pass def __setslice__(self, i, j, y): # real signature unknown; restored from __doc__ """ x.__setslice__(i, j, y) <==> x[i:j]=y Use of negative indices is not supported. """ pass def __sizeof__(self): # real signature unknown; restored from __doc__ """ L.__sizeof__() -- size of L in memory, in bytes """ pass __hash__ = None
字符串--列表互相转换
# 字符串转换列表 li = list("asdfasdfasdf"), 内部使用for循环 # s = "pouaskdfauspdfiajsdkfj" # new_li = list(s) # print(new_li) # 列表转换成字符串, # 需要自己写for循环一个一个处理: 既有数字又有字符串 # li = [11,22,33,"123","alex"] # s = "" # for i in li: # s = s + str(i) # print(s) # 直接使用字符串join方法:列表中的元素只有字符串 # li = ["123","alex"] # v = "".join(li) # print(v)
元组 有序
创建元组:
# 元组,元素不可被修改,不能被增加或者删除
# tuple
# tu = (11,22,33,44)
# tu.count(22),获取指定元素在元组中出现的次数
基本操作:
- 索引
- 切片
- 循环
- 长度
- 包含
####################################### 操作方法 #######################################
# 1. 书写格式
# tu = (111,"alex",(11,22),[(33,44)],True,33,44,)
# 一般写元组的时候,推荐在最后加入 ,
# 元素不可被修改,不能被增加或者删除
# 2. 索引
# v = tu[0]
# print(v)
# 3. 切片
# v = tu[0:2]
# print(v)
# 4. 可以被for循环,可迭代对象
# for item in tu:
# print(item)
# 5. 转换
# s = "asdfasdf0"
# li = ["asdf","asdfasdf"]
# tu = ("asdf","asdf")
#
# v = tuple(s)
# print(v)
# v = tuple(li)
# print(v)
# v = list(tu)
# print(v)
# v = "_".join(tu)
# print(v)
# li = ["asdf","asdfasdf"]
# li.extend((11,22,33,))
# print(li)
# 6.元组的一级元素不可修改/删除/增加
# tu = (111,"alex",(11,22),[(33,44)],True,33,44,)
# # 元组,有序。
# # v = tu[3][0][0]
# # print(v)
# # v=tu[3]
# # print(v)
# tu[3][0] = 567
## print(tu)
#以10作为开始序号,依次输出序号和对应值
tu = ('alex', 'eric', 'rain')
for idx, elem in enumerate(tu, 10):
print(idx, elem)
lass tuple(object): """ tuple() -> empty tuple tuple(iterable) -> tuple initialized from iterable's items If the argument is a tuple, the return value is the same object. """ def count(self, value): # real signature unknown; restored from __doc__ """ T.count(value) -> integer -- return number of occurrences of value """ return 0 def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__ """ T.index(value, [start, [stop]]) -> integer -- return first index of value. Raises ValueError if the value is not present. """ return 0 def __add__(self, y): # real signature unknown; restored from __doc__ """ x.__add__(y) <==> x+y """ pass def __contains__(self, y): # real signature unknown; restored from __doc__ """ x.__contains__(y) <==> y in x """ pass def __eq__(self, y): # real signature unknown; restored from __doc__ """ x.__eq__(y) <==> x==y """ pass def __getattribute__(self, name): # real signature unknown; restored from __doc__ """ x.__getattribute__('name') <==> x.name """ pass def __getitem__(self, y): # real signature unknown; restored from __doc__ """ x.__getitem__(y) <==> x[y] """ pass def __getnewargs__(self, *args, **kwargs): # real signature unknown pass def __getslice__(self, i, j): # real signature unknown; restored from __doc__ """ x.__getslice__(i, j) <==> x[i:j] Use of negative indices is not supported. """ pass def __ge__(self, y): # real signature unknown; restored from __doc__ """ x.__ge__(y) <==> x>=y """ pass def __gt__(self, y): # real signature unknown; restored from __doc__ """ x.__gt__(y) <==> x>y """ pass def __hash__(self): # real signature unknown; restored from __doc__ """ x.__hash__() <==> hash(x) """ pass def __init__(self, seq=()): # known special case of tuple.__init__ """ tuple() -> empty tuple tuple(iterable) -> tuple initialized from iterable's items If the argument is a tuple, the return value is the same object. # (copied from class doc) """ pass def __iter__(self): # real signature unknown; restored from __doc__ """ x.__iter__() <==> iter(x) """ pass def __len__(self): # real signature unknown; restored from __doc__ """ x.__len__() <==> len(x) """ pass def __le__(self, y): # real signature unknown; restored from __doc__ """ x.__le__(y) <==> x<=y """ pass def __lt__(self, y): # real signature unknown; restored from __doc__ """ x.__lt__(y) <==> x<y """ pass def __mul__(self, n): # real signature unknown; restored from __doc__ """ x.__mul__(n) <==> x*n """ pass @staticmethod # known case of __new__ def __new__(S, *more): # real signature unknown; restored from __doc__ """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass def __ne__(self, y): # real signature unknown; restored from __doc__ """ x.__ne__(y) <==> x!=y """ pass def __repr__(self): # real signature unknown; restored from __doc__ """ x.__repr__() <==> repr(x) """ pass def __rmul__(self, n): # real signature unknown; restored from __doc__ """ x.__rmul__(n) <==> n*x """ pass def __sizeof__(self): # real signature unknown; restored from __doc__ """ T.__sizeof__() -- size of T in memory, in bytes """ pass tuple
字典(无序)
创建字典:
# dict
# dic = {
# "k1": 'v1',
# "k2": 'v2'
# }
常用操作:
- 索引
- 新增
- 删除
- 键、值、键值对 dict.keys() dict.values() dict.items()
- 循环
- 长度
# 1 根据序列,创建字典,并指定统一的值
# v = dict.fromkeys(["k1",123,"999"],123)
# print(v)
# 2 根据Key获取值,key不存在时,可以指定默认值(None)
# v = dic['k11111']
# print(v)
# v = dic.get('k1',111111)
# print(v)
# 3 删除并获取值
# dic = {
# "k1": 'v1',
# "k2": 'v2'
# }
# v = dic.pop('k1',90)
# print(dic,v)
# k,v = dic.popitem() #随机删除键值对,返回对应值
# print(dic,k,v)
# 4 设置值,
# 已存在,不设置,获取当前key对应的值
# 不存在,设置,获取当前key对应的值
# dic = {
# "k1": 'v1',
# "k2": 'v2'
# }
# v = dic.setdefault('k1111','123')
# print(dic,v)
# 5 更新
# dic = {
# "k1": 'v1',
# "k2": 'v2'
# }
# dic.update({'k1': '111111','k3': 123}) 已存在的覆盖,不存在的key更新上
# print(dic)
# dic.update(k1=123,k3=345,k5="asdf")
# print(dic)
# 最常用的有: 6 keys() 7 values() 8 items() get update
# 1、基本机构 # info = { # "k1": "v1", # 键值对 # "k2": "v2" # } #### 2 字典的value可以是任何值 # info = { # "k1": 18, # "k2": True, # "k3": [ # 11, # [], # (), # 22, # 33, # { # 'kk1': 'vv1', # 'kk2': 'vv2', # 'kk3': (11,22), # } # ], # "k4": (11,22,33,44) # } # print(info) #### 3 列表、字典不能作为字典的key # info ={ # 1: 'asdf', # "k1": 'asdf', # True: "123", # # [11,22]: 123 # (11,22): 123, # # {'k1':'v1'}: 123 # # } # print(info) # 4 字典无序 # info = { # "k1": 18, # "k2": True, # "k3": [ # 11, # [], # (), # 22, # 33, # { # 'kk1': 'vv1', # 'kk2': 'vv2', # 'kk3': (11,22), # } # ], # "k4": (11,22,33,44) # } # print(info) # 5、索引方式找到指定元素 # info = { # "k1": 18, # 2: True, # "k3": [ # 11, # [], # (), # 22, # 33, # { # 'kk1': 'vv1', # 'kk2': 'vv2', # 'kk3': (11,22), # } # ], # "k4": (11,22,33,44) # } # # v = info['k1'] # # print(v) # # v = info[2] # # print(v) # v = info['k3'][5]['kk3'][0] # print(v) # 6 字典支持 del 删除 # info = { # "k1": 18, # 2: True, # "k3": [ # 11, # [], # (), # 22, # 33, # { # 'kk1': 'vv1', # 'kk2': 'vv2', # 'kk3': (11,22), # } # ], # "k4": (11,22,33,44) # } # del info['k1'] # # del info['k3'][5]['kk1'] # print(info) # 7 for循环 # dict # info = { # "k1": 18, # 2: True, # "k3": [ # 11, # [], # (), # 22, # 33, # { # 'kk1': 'vv1', # 'kk2': 'vv2', # 'kk3': (11,22), # } # ], # "k4": (11,22,33,44) # } # for item in info: # print(item) # # for item in info.keys(): # print(item) # for item in info.values(): # print(item) # for item in info.keys(): # print(item,info[item]) # for k,v in info.items(): # print(k,v) # True 1 False 0 # info ={ # "k1": 'asdf', # True: "123", # # [11,22]: 123 # (11,22): 123, # # {'k1':' v1'}: 123 # # } # print(info)
class dict(object): """ dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2) """ def clear(self): # real signature unknown; restored from __doc__ """ 清除内容 """ """ D.clear() -> None. Remove all items from D. """ pass def copy(self): # real signature unknown; restored from __doc__ """ 浅拷贝 """ """ D.copy() -> a shallow copy of D """ pass @staticmethod # known case def fromkeys(S, v=None): # real signature unknown; restored from __doc__ """ dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v. v defaults to None. """ pass def get(self, k, d=None): # real signature unknown; restored from __doc__ """ 根据key获取值,d是默认值 """ """ D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None. """ pass def has_key(self, k): # real signature unknown; restored from __doc__ """ 是否有key """ """ D.has_key(k) -> True if D has a key k, else False """ return False def items(self): # real signature unknown; restored from __doc__ """ 所有项的列表形式 """ """ D.items() -> list of D's (key, value) pairs, as 2-tuples """ return [] def iteritems(self): # real signature unknown; restored from __doc__ """ 项可迭代 """ """ D.iteritems() -> an iterator over the (key, value) items of D """ pass def iterkeys(self): # real signature unknown; restored from __doc__ """ key可迭代 """ """ D.iterkeys() -> an iterator over the keys of D """ pass def itervalues(self): # real signature unknown; restored from __doc__ """ value可迭代 """ """ D.itervalues() -> an iterator over the values of D """ pass def keys(self): # real signature unknown; restored from __doc__ """ 所有的key列表 """ """ D.keys() -> list of D's keys """ return [] def pop(self, k, d=None): # real signature unknown; restored from __doc__ """ 获取并在字典中移除 """ """ D.pop(k[,d]) -> v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised """ pass def popitem(self): # real signature unknown; restored from __doc__ """ 获取并在字典中移除 """ """ D.popitem() -> (k, v), remove and return some (key, value) pair as a 2-tuple; but raise KeyError if D is empty. """ pass def setdefault(self, k, d=None): # real signature unknown; restored from __doc__ """ 如果key不存在,则创建,如果存在,则返回已存在的值且不修改 """ """ D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """ pass def update(self, E=None, **F): # known special case of dict.update """ 更新 {'name':'alex', 'age': 18000} [('name','sbsbsb'),] """ """ D.update([E, ]**F) -> None. Update D from dict/iterable E and F. If E present and has a .keys() method, does: for k in E: D[k] = E[k] If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k] """ pass def values(self): # real signature unknown; restored from __doc__ """ 所有的值 """ """ D.values() -> list of D's values """ return [] def viewitems(self): # real signature unknown; restored from __doc__ """ 所有项,只是将内容保存至view对象中 """ """ D.viewitems() -> a set-like object providing a view on D's items """ pass def viewkeys(self): # real signature unknown; restored from __doc__ """ D.viewkeys() -> a set-like object providing a view on D's keys """ pass def viewvalues(self): # real signature unknown; restored from __doc__ """ D.viewvalues() -> an object providing a view on D's values """ pass def __cmp__(self, y): # real signature unknown; restored from __doc__ """ x.__cmp__(y) <==> cmp(x,y) """ pass def __contains__(self, k): # real signature unknown; restored from __doc__ """ D.__contains__(k) -> True if D has a key k, else False """ return False def __delitem__(self, y): # real signature unknown; restored from __doc__ """ x.__delitem__(y) <==> del x[y] """ pass def __eq__(self, y): # real signature unknown; restored from __doc__ """ x.__eq__(y) <==> x==y """ pass def __getattribute__(self, name): # real signature unknown; restored from __doc__ """ x.__getattribute__('name') <==> x.name """ pass def __getitem__(self, y): # real signature unknown; restored from __doc__ """ x.__getitem__(y) <==> x[y] """ pass def __ge__(self, y): # real signature unknown; restored from __doc__ """ x.__ge__(y) <==> x>=y """ pass def __gt__(self, y): # real signature unknown; restored from __doc__ """ x.__gt__(y) <==> x>y """ pass def __init__(self, seq=None, **kwargs): # known special case of dict.__init__ """ dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2) # (copied from class doc) """ pass def __iter__(self): # real signature unknown; restored from __doc__ """ x.__iter__() <==> iter(x) """ pass def __len__(self): # real signature unknown; restored from __doc__ """ x.__len__() <==> len(x) """ pass def __le__(self, y): # real signature unknown; restored from __doc__ """ x.__le__(y) <==> x<=y """ pass def __lt__(self, y): # real signature unknown; restored from __doc__ """ x.__lt__(y) <==> x<y """ pass @staticmethod # known case of __new__ def __new__(S, *more): # real signature unknown; restored from __doc__ """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass def __ne__(self, y): # real signature unknown; restored from __doc__ """ x.__ne__(y) <==> x!=y """ pass def __repr__(self): # real signature unknown; restored from __doc__ """ x.__repr__() <==> repr(x) """ pass def __setitem__(self, i, y): # real signature unknown; restored from __doc__ """ x.__setitem__(i, y) <==> x[i]=y """ pass def __sizeof__(self): # real signature unknown; restored from __doc__ """ D.__sizeof__() -> size of D in memory, in bytes """ pass __hash__ = None dict
数字 字符串 列表 元组 字典 bool整理总结
####################### 整理 ################# # 一、数字 # int(..) # 二、字符串 # replace/find/join/strip/startswith/split/upper/lower/format # tempalte = "i am {name}, age : {age}" # # v = tempalte.format(name='alex',age=19) # v = tempalte.format(**{"name": 'alex','age': 19}) # print(v) # 三、列表 # append、extend、insert # 索引、切片、循环 # 四、元组 # 忽略 # 索引、切片、循环 以及元素不能被修改 # 五、字典 # get/update/keys/values/items # for,索引 # dic = { # "k1": 'v1' # } # v = "k1" in dic # print(v) # v = "v1" in dic.values() # print(v) # 六、布尔值 # 0 1 # bool(...) # None "" () [] {} 0 ==> False
集合(无序)