基本数据类型
一、整数类型(int)
32位机器,整数的位数为32位,取值范围为-2**31~2**31-1,即-2147483648~2147483647
64位机器,整数的位数是64位,取值范围位-2**63~2**63-1,即-9223372036854775808~9223372036854775807
bit_lenth():当十进制用二进制表示时,最少使用的位数
a = 6 b = 10 c = 100 print(a.bit_length()) print(b.bit_length()) print(c.bit_length()) #输出结果:3,4,7
二、布尔值类型(bool)
字符串转化位布尔值:bool(str),当字符串为空字符串,转化为False,否则转化为True
a = 'afds,bnk' b = '' c = ' ' print(bool(a),bool(b),bool(c)) #输出结果:True,False,True
a = '' if a: print('正确') else: print('错误') #输出结果:错误
三、字符串类型(str):对字符串进行操作无法改变原字符串
1、索引:索引(下标、index)从0开始,即第一个元素的索引为0,也可以从后面开始索引,最后一个元素的索引为-1
a = 'afhd,jhg:vnv' print(a[0],a[4],a[-1],a[-4]) #输出结果:a , v :
2、切片:[起始位置:结束位置:步长] ,特点:步长可以为空,默认为1;a[0:]表示从第1个元素切到最后1个元素;a[-1:]
使用方法:先确定第一个切片的下标,然后确定最后一个切片的下标,正切则步长用正数表示,反切则步长用负数表示
a = '你好,欢迎来到python世界!' #打印你好 print(a[0:2]) print(a[:-14]) #打印python print(a[7:13]) print(a[-9:-3]) #打印好欢来 print(a[1:6:2]) print(a[-15:-10:2]) #打印届nhy print(a[-2:-9:-2]) print(a[14:7:-2])
3、首字母大写:a.capitalize()
a = 'abc' print(a.capitalize()) #输出:Abc
4、大小写翻转:a.swapcase()
a = 'abC' print(a.swapcase()) #输出:ABc
5、每个单词的首字母大写:a.title(),以非英文字母为间隔,每个单词的首字母大写
a = 'abc:fh,dg dsa .das' print(a.title()) #输出:Abc:Fh,Dg Dsa .Das
6、内容居中,空白处填充:a.center(长度,'填充内容'),填充内容为空则默认用空格填充,优先填充右边
a = '12345' print(a.center(10,'*')) #输出结果:**12345***
7、将tab键变成空格:如果tab键前面的字符长度不足8个,则将tab键变成空格,使长度变成8;如果tab键前面的字符长度>=8,则将将tab键变成空格,使长度变成16
a = "hqwe " print(a.expandtabs()) #输出结果:hqwe四个空格 a = "abcdefgh " print(a.expandtabs()) #输出结果:abcdehgh八个空格
8、判断以.....开头、以......结尾:a.startswith('元素',起始下标,结束下标),起始下标、结束下标可以不填,则默认为整个字符串;a.endswith('元素',起始下标,结束下标),其中‘元素’可以为一个字母或多个字母
a = 'svxcbdfsdgh' print(a.startswith('s',)) print(a.startswith('s',1,3)) print(a.startswith('s',0,3)) print(a.endswith('h')) print(a.endswith('h',-1)) print(a.endswith('h',-1,11)) #输出结果: #True #False #True #True #True #True
9.计算字符串中出现元素的个数:a.count('元素',起始下标,结束下标),起始下标、结束下标可以不填,则默认为整个字符串
a = 'svxcbsdfsdgh' print(a.count('s')) print(a.count('s',0,6)) #输出结果:
#3
#2
10、寻找字符串中的元素是否存在:a.find('元素',起始下标,结束下标),找到则返回元素的索引(只寻找第一个匹配的元素),找不到则返回-1,元素可以为一个字母或多个字母
a.index('元素',起始下标,结束下标),找到则返回元素的索引(只寻找第一个匹配的元素),找不到则报错,元素可以为一个字母或多个字母
a = 'abcabcabc' print(a.find('bc')) print(a.index('abc')) print(a.find('c',3,6)) print(a.find('cb')) print(a.index('ca',0,2)) #输出: #1 #0 #5 #-1 #报错
11、切割:a.spilt('元素',次数),被切割的元素会消失,次数为切割次数,次数可以不填,默认全部切割
a = 'abc abc abc' print(a.split('b')) print(a.split('b',1)) print(a.split(' ')) #输出结果: #['a', 'c a', 'c a', 'c'] #['a', 'c abc abc'] #['abc', 'abc', 'abc']
12.代替:a.replace('旧元素','新元素',次数),次数为替代的次数,次数可以不填,默认全部替代
a = 'abcahg123aa' print(a.replace('a','w')) print(a.replace('a','w',2)) #输出结果: #wbcwhg123ww #wbcwhg123aa
13、判断是否以字母或数字组成:a.isalnum();判断是否以字母组成:a.isalpha();判断是否以字母组成:a.isdigit()
a = 'asd123' print(a.isalnum()) print(a.isalpha()) print(a.isdigit()) #输出结果: #True #False #False
14、消除:a.strip('可迭代对象'),从头尾开始清除可迭代对象,遇到非迭代对象则停止
a.lstrip('可迭代对象'),从左边消除可迭代对象,遇到非迭代对象则停止
a.rstrip('可迭代对象'),从右边消除可迭代对象,遇到非迭代对象则停止
a = 'safg31342fhsdf' print(a.strip('sahf')) #输出:g31342fhsd print(a.lstrip('sfd')) #输出:afg31342fhsdf print(a.rstrip('adf')) #输出:safg31342fhs
15、格式化输出:三种方式
方式一:a = 'name:{},sex:{},hobbie:{}'.format('a','b','c'),必须一一对应
方式二:a = 'name:{0},sex:{1},hobbie:{2},job:{1}'.format('a','b','c'),不用一一对应,但需要按顺序
方式三:a = 'name:{name},sex:{age},hobbie:{sex}:job:{sex}'.format('name = a','age = b','sex = c'),不用一一对应,也不用按顺序
a = 'name:{},sex:{},hobbie:{}'.format('Peter','man','basketball') b = 'name:{0},sex:{2},hobbie:{1},name:{0}'.format('Peter','basketball','man') c = 'name:{n},sex:{s}.hobbie:{h},name:{n}'.format(h = 'baskerball',n = 'Peter',s = 'man') #输出结果: #name:Peter,sex:man,hobbie:basketball #name:Peter,sex:man,hobbie:basketball,name:Peter #name:Peter,sex:man.hobbie:baskerball,name:Peter
def capitalize(self): # real signature unknown; restored from __doc__ """ S.capitalize() -> str Return a capitalized version of S, i.e. make the first character have upper case and the rest lower case. """ return "" def casefold(self): # real signature unknown; restored from __doc__ """ S.casefold() -> str Return a version of S suitable for caseless comparisons. """ return "" def center(self, width, fillchar=None): # real signature unknown; restored from __doc__ """ S.center(width[, fillchar]) -> str Return S centered in a string of length width. Padding is done using the specified fill character (default is a space) """ return "" def count(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ """ S.count(sub[, start[, end]]) -> int Return the number of non-overlapping occurrences of substring sub in string S[start:end]. Optional arguments start and end are interpreted as in slice notation. """ return 0 def encode(self, encoding='utf-8', errors='strict'): # real signature unknown; restored from __doc__ """ S.encode(encoding='utf-8', errors='strict') -> bytes Encode S using the codec registered for encoding. Default encoding is 'utf-8'. errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors raise a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and 'xmlcharrefreplace' as well as any other name registered with codecs.register_error that can handle UnicodeEncodeErrors. """ return b"" def endswith(self, suffix, start=None, end=None): # real signature unknown; restored from __doc__ """ S.endswith(suffix[, start[, end]]) -> bool Return True if S ends with the specified suffix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. suffix can also be a tuple of strings to try. """ return False def expandtabs(self, tabsize=8): # real signature unknown; restored from __doc__ """ S.expandtabs(tabsize=8) -> str Return a copy of S where all tab characters are expanded using spaces. If tabsize is not given, a tab size of 8 characters is assumed. """ return "" def find(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ """ S.find(sub[, start[, end]]) -> int Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure. """ return 0 def format(self, *args, **kwargs): # known special case of str.format """ S.format(*args, **kwargs) -> str Return a formatted version of S, using substitutions from args and kwargs. The substitutions are identified by braces ('{' and '}'). """ pass def format_map(self, mapping): # real signature unknown; restored from __doc__ """ S.format_map(mapping) -> str Return a formatted version of S, using substitutions from mapping. The substitutions are identified by braces ('{' and '}'). """ return "" def index(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ """ S.index(sub[, start[, end]]) -> int Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation. Raises ValueError when the substring is not found. """ return 0 def isalnum(self): # real signature unknown; restored from __doc__ """ S.isalnum() -> bool Return True if all characters in S are alphanumeric and there is at least one character in S, False otherwise. """ return False def isalpha(self): # real signature unknown; restored from __doc__ """ S.isalpha() -> bool Return True if all characters in S are alphabetic and there is at least one character in S, False otherwise. """ return False def isdecimal(self): # real signature unknown; restored from __doc__ """ S.isdecimal() -> bool Return True if there are only decimal characters in S, False otherwise. """ return False def isdigit(self): # real signature unknown; restored from __doc__ """ S.isdigit() -> bool Return True if all characters in S are digits and there is at least one character in S, False otherwise. """ return False def isidentifier(self): # real signature unknown; restored from __doc__ """ S.isidentifier() -> bool Return True if S is a valid identifier according to the language definition. Use keyword.iskeyword() to test for reserved identifiers such as "def" and "class". """ return False def islower(self): # real signature unknown; restored from __doc__ """ S.islower() -> bool Return True if all cased characters in S are lowercase and there is at least one cased character in S, False otherwise. """ return False def isnumeric(self): # real signature unknown; restored from __doc__ """ S.isnumeric() -> bool Return True if there are only numeric characters in S, False otherwise. """ return False def isprintable(self): # real signature unknown; restored from __doc__ """ S.isprintable() -> bool Return True if all characters in S are considered printable in repr() or S is empty, False otherwise. """ return False def isspace(self): # real signature unknown; restored from __doc__ """ S.isspace() -> bool Return True if all characters in S are whitespace and there is at least one character in S, False otherwise. """ return False def istitle(self): # real signature unknown; restored from __doc__ """ S.istitle() -> bool Return True if S is a titlecased string and there is at least one character in S, i.e. upper- and titlecase characters may only follow uncased characters and lowercase characters only cased ones. Return False otherwise. """ return False def isupper(self): # real signature unknown; restored from __doc__ """ S.isupper() -> bool Return True if all cased characters in S are uppercase and there is at least one cased character in S, False otherwise. """ return False def join(self, iterable): # real signature unknown; restored from __doc__ """ S.join(iterable) -> str Return a string which is the concatenation of the strings in the iterable. The separator between elements is S. """ return "" def ljust(self, width, fillchar=None): # real signature unknown; restored from __doc__ """ S.ljust(width[, fillchar]) -> str Return S left-justified in a Unicode string of length width. Padding is done using the specified fill character (default is a space). """ return "" def lower(self): # real signature unknown; restored from __doc__ """ S.lower() -> str Return a copy of the string S converted to lowercase. """ return "" def lstrip(self, chars=None): # real signature unknown; restored from __doc__ """ S.lstrip([chars]) -> str Return a copy of the string S with leading whitespace removed. If chars is given and not None, remove characters in chars instead. """ return "" def maketrans(self, *args, **kwargs): # real signature unknown """ Return a translation table usable for str.translate(). If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters to Unicode ordinals, strings or None. Character keys will be then converted to ordinals. If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result. """ pass def partition(self, sep): # real signature unknown; restored from __doc__ """ S.partition(sep) -> (head, sep, tail) Search for the separator sep in S, and return the part before it, the separator itself, and the part after it. If the separator is not found, return S and two empty strings. """ pass def replace(self, old, new, count=None): # real signature unknown; restored from __doc__ """ S.replace(old, new[, count]) -> str Return a copy of S with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced. """ return "" def rfind(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ """ S.rfind(sub[, start[, end]]) -> int Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure. """ return 0 def rindex(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ """ S.rindex(sub[, start[, end]]) -> int Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation. Raises ValueError when the substring is not found. """ return 0 def rjust(self, width, fillchar=None): # real signature unknown; restored from __doc__ """ S.rjust(width[, fillchar]) -> str Return S right-justified in a string of length width. Padding is done using the specified fill character (default is a space). """ return "" def rpartition(self, sep): # real signature unknown; restored from __doc__ """ S.rpartition(sep) -> (head, sep, tail) Search for the separator sep in S, starting at the end of S, and return the part before it, the separator itself, and the part after it. If the separator is not found, return two empty strings and S. """ pass def rsplit(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__ """ S.rsplit(sep=None, maxsplit=-1) -> list of strings Return a list of the words in S, using sep as the delimiter string, starting at the end of the string and working to the front. If maxsplit is given, at most maxsplit splits are done. If sep is not specified, any whitespace string is a separator. """ return [] def rstrip(self, chars=None): # real signature unknown; restored from __doc__ """ S.rstrip([chars]) -> str Return a copy of the string S with trailing whitespace removed. If chars is given and not None, remove characters in chars instead. """ return "" def split(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__ """ S.split(sep=None, maxsplit=-1) -> list of strings Return a list of the words in S, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done. If sep is not specified or is None, any whitespace string is a separator and empty strings are removed from the result. """ return [] def splitlines(self, keepends=None): # real signature unknown; restored from __doc__ """ S.splitlines([keepends]) -> list of strings Return a list of the lines in S, breaking at line boundaries. Line breaks are not included in the resulting list unless keepends is given and true. """ return [] def startswith(self, prefix, start=None, end=None): # real signature unknown; restored from __doc__ """ S.startswith(prefix[, start[, end]]) -> bool Return True if S starts with the specified prefix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. prefix can also be a tuple of strings to try. """ return False def strip(self, chars=None): # real signature unknown; restored from __doc__ """ S.strip([chars]) -> str Return a copy of the string S with leading and trailing whitespace removed. If chars is given and not None, remove characters in chars instead. """ return "" def swapcase(self): # real signature unknown; restored from __doc__ """ S.swapcase() -> str Return a copy of S with uppercase characters converted to lowercase and vice versa. """ return "" def title(self): # real signature unknown; restored from __doc__ """ S.title() -> str Return a titlecased version of S, i.e. words start with title case characters, all remaining cased characters have lower case. """ return "" def translate(self, table): # real signature unknown; restored from __doc__ """ S.translate(table) -> str Return a copy of the string S in which each character has been mapped through the given translation table. The table must implement lookup/indexing via __getitem__, for instance a dictionary or list, mapping Unicode ordinals to Unicode ordinals, strings, or None. If this operation raises LookupError, the character is left untouched. Characters mapped to None are deleted. """ return "" def upper(self): # real signature unknown; restored from __doc__ """ S.upper() -> str Return a copy of S converted to uppercase. """ return "" def zfill(self, width): # real signature unknown; restored from __doc__ """ S.zfill(width) -> str Pad a numeric string S with zeros on the left, to fill a field of the specified width. The string S is never truncated. """ return ""
四、列表(list):对列表进行增删改,会改变原列表
1、增:3种方式:.append(元素),元素可以为数字、布尔值、字符串、列表、元组、字典,在列表末端加入元素
.insert(位置,元素),元素可以为数字、布尔值、字符串、列表、元组、字典,在指定位置加入元素
.extend(元素),元素为可迭代对象,可以为数字、布尔值、字符串、列表、元组、字典,在列表末端依次加入
li = [1,2,'a',True,('b',3,5)] li.append('abc') print(li) #输出结果:[1, 2, 'a', True, ('b', 3, 5), 'abc'] li = [1,2,'a',True,('b',3,5)] li.insert(1,'你好') print(li) #输出结果:[1, '你好', 2, 'a', True, ('b', 3, 5)] li = [1,2,'a',True,('b',3,5)] li.extend('aoe') print(li) #输出结果:[1, 2, 'a', True, ('b', 3, 5), 'a', 'o', 'e']
2、删:4种方法:.pop(元素位置),pop删除会生成一个结果,结果为删除的元素
.remove('元素'),不会生成结果, 有多个相同的元素,只会删除第一个匹配的元素
.clear(),情况列表所有数据,变成空列表
del li[起始位置:结束位置:步长],步长可以为空,默认为1,del li 直接把列表删除
li = [1,2,'a',True,('b',3,5)] a = li.pop(1) print(a) print(li) #输出结果: #1 #[1, 'a', True, ('b', 3, 5)] li = [1,2,'a',True,('b',3,5)] li.remove(1) print(li) #输出结果:[2, 'a', True, ('b', 3, 5)] li = [1,2,'a',True,('b',3,5)] li.clear() print(li) #输出结果:[] li = [1,2,'a',True,('b',3,5)] del li[0:3:2] print(li) #输出结果:[2,True,('b',3,5)]
3、改:li[元素下标] = 新元素,新元素可以为数字、布尔值、字符串、列表、元组、字典
li[起始位置:结束位置,新元素],首先会把起始位置到结束位置的元素删除,然后迭代地增加新元素
li = [1,3,'a','你',True,(1,2,'w'),[3,9,'l'],'d'] li[2] = 'ap' print(li) #输出结果:[1, 3, 'ap', '你', True, (1, 2, 'w'), [3, 9, 'l'], 'd'] li = [1,3,'a','你',True,(1,2,'w'),[3,9,'l'],'d'] li[1:3] = 'oip' print(li) #输出结果:[1, 'o', 'i', 'p', '你', True, (1, 2, 'w'), [3, 9, 'l'], 'd']
4、查:按索引查:li[元素位置];按切片查:li[起始位置:结束位置:步长];li.index(元素,起始位置,结束位置),通过元素找索引,起始位置、结束位置可以不填,默认为整个列表
li = [1,3,'a','你',True,(1,2,'w'),[3,9,'l'],'d'] print(li[-1]) print(li[6:1:-2]) #输出结果: #d #[[3, 9, 'l'], True, 'a']
li = [1,3,'a',('c','d',7),'fd'] print(li.index(3)) #输出结果:1
5、排序:正序:li.sort(),数字由小到大排序,字母则按ascii码排序;反转:li.reverse(),将列表的元素倒过来排序
li = [1,3,6,2,9,8,4,7,5,0] li.sort() print(li) #输出结果:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] li = [1,3,6,2,9,8,4,7,5,0] li.reverse() print(li) #输出结果:[0, 5, 7, 4, 8, 9, 2, 6, 3, 1] li = [1,3,6,2,9,8,4,7,5,0] li.sort(reverse = True) print(li) #输出结果:[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
6、计算元素出现次数:a.count(元素),字符串的count可以切片,列表的count不可以切片
a = [1,2,3,4,5] print(a.count(2)) #输出结果:1
def append(self, p_object): # real signature unknown; restored from __doc__ """ L.append(object) -> None -- append object to end """ pass def clear(self): # real signature unknown; restored from __doc__ """ L.clear() -> None -- remove all items from L """ pass def copy(self): # real signature unknown; restored from __doc__ """ L.copy() -> list -- a shallow copy of L """ return [] 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) -> None -- 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) -> None -- 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, key=None, reverse=False): # real signature unknown; restored from __doc__ """ L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE* """ pass
五、for循环:for i in 可迭代对象:,字符串、列表、元组、字典、range()都为可迭代对象
for i in 'asda': print(i) #输出结果: #a #s #d #a for i in range(1,5): print(i) #输出结果 #1 #2 #3 #4
六、元组(tuple):元组的元素不能修改,但是元素里面的元素可以修改
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
七、字典(dic):无序、以键值对形式存在、是python唯一具有映射关系的数据类型
字典的键必须是可哈希(不可变的数据类型)的,而且键必须唯一
不可变的数据类型:数字、布尔值、字符串、元组;可变的数据类型:列表、字典、集合(set)
1、增:方法一:dic['abc'] = '123',字典里没有的键会增加,字典里有的键则会把值覆盖
方法二:dic.setdefault(键,值),字典里没有的键会增加,字典里已有的键的值不会变,值可以不填,默认为None
dic = {'name':'abc','age':18} dic['sex'] = 'man' print(dic) dic['name'] = 'qwe' print(dic) #输出结果: #{'name': 'abc', 'age': 18, 'sex': 'man'} #{'name': 'qwe', 'age': 18, 'sex': 'man'} dic = {'name':'abc','age':18} dic.setdefault('sex','man') print(dic) dic.setdefault('name','qwe') print(dic) #输出结果: #{'name': 'abc', 'age': 18, 'sex': 'man'} #{'name': 'abc', 'age': 18, 'sex': 'man'}
2、删:dic.pop(键),删除一个键值对,返回删除键对应的值,如果键不存在,则会报错,此时可以在写成dic.pop(键,内容),如果键不存在,则会返回内容,不会报错
dic.popitem(),随机删除一个键值对,将删除的键值以元组的形式 返回
dic.clear(),清空字典,返回值为None;del dic,删除整个字典
del dic[键],删除字典的一个键值对,没有返回值,如果键不存在,报错
dic = {'name':'abc','age':18} print(dic.pop('name')) #abc print(dic) #{'age':18} print(dic.pop('asd','mmm')) #mmm print(dic) #{'age':18} dic = {'name':'abc','age':18} print(dic.popitem()) #('age':18) print(dic) #{'name':'abc'} dic = {'name':'abc','age':18} print(dic.clear()) #None print(dic) #{} dic = {'name':'abc','age':18} del dic['name'] print(dic) #{'age': 18}
3、改:dic[键] = 值,如果键存在,则改值,如果键没有,则新增键值对
dic1 = {},dic2 = {},dic1.update(dic2),将dic2的内容更新到dic1,即将dic2的键值对新增并覆盖到dic1
dic = {'name':'abc','age':18,'job':'teacher'} dic['name'] = '天空' print(dic) #{'name': '天空', 'age': 18, 'job': 'teacher'} dic1 = {'name':'A','age':18,'sex':'man'} dic2 = {'name':'B','hobbie':'swim'} dic1.update(dic2) print(dic1) #{'name': 'B', 'age': 18, 'sex': 'man', 'hobbie': 'swim'}
4、查:dic[键],如果键没有,报错
dic.get(键,内容),如果键存在,返回键对应的值,如果键存在返回内容,内容可以不填,如果键不存在,则返回None
dic = {'name':'abc','age':18,'job':'teacher'} print(dic['name']) #abc print(dic.get('namea')) #None print(dic.get('namea','没有')) #没有
5、其它操作:dic.items(),返回值是一个列表,这个列表由元组组成,元组为dic的键值对
dic.keys(),返回值是一个列表,列表由dic的键组成
dic,values(),返回值是一个列表,列表由dic的值组成
dic = {'a':1,'b':2,'c':3,'d':4} print(dic.keys()) #dict_keys(['a', 'b', 'c', 'd']) print(dic.values()) #dict_values([1, 2, 3, 4]) print(dic.items()) #dict_items([('a', 1), ('b', 2), ('c', 3), ('d', 4)])
6、字典的循环:for i in dic.keys(),返回键;
for i in dic.values(),返回值;
for i in dic.items(),返回键值对的元组;
for i,j in dic.items(),返回键、值;
for i in dic,返回键;
dic = {"name":"guku","age":18,"sex":"male"} for i in dic.keys(): print(i) #name #age #sex for i in dic.values(): print(i) #guku #18 #male for i in dic.items(): print(i) #('name', 'guku') #('age', 18) #('sex', 'male') for i,j in dic.items(): print(i,j) #name guku #age 18 #sex male for i in dic: print(i) #name #age #sex
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(*args, **kwargs): # real signature unknown """ Returns a new dict with keys from iterable and values equal to value. """ pass def get(self, k, d=None): # real signature unknown; restored from __doc__ """ D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None. """ pass def items(self): # real signature unknown; restored from __doc__ """ D.items() -> a set-like object providing a view on D's items """ pass def keys(self): # real signature unknown; restored from __doc__ """ D.keys() -> a set-like object providing a view on D's keys """ pass 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__ """ 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 """ D.update([E, ]**F) -> None. Update D from dict/iterable E and F. If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then 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() -> an object providing a view on D's values """ pass