基本数据类型

一、整数类型(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 = ''
print(a.center(10,'*'))
#输出结果:**12345***

  7、将tab键变成空格:如果tab键前面的字符长度不足8个,则将tab键变成空格,使长度变成8;如果tab键前面的字符长度>=8,则将将tab键变成空格,使长度变成16

a = "hqwe\t"
print(a.expandtabs())
#输出结果:hqwe四个空格
a = "abcdefgh\t"
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
#报错

  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 ""

str的方法集合

四、列表(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, '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)
#输出结果
#
#
#
#

六、元组(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
#
#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

字典的方法集合

Python学习(三) —— 基本数据类型的更多相关文章

  1. Python学习笔记 - day3 - 数据类型及运算符

    Python的数据类型 计算机顾名思义就是可以做数学计算的机器,因此,计算机程序理所当然地可以处理各种数值.但是,计算机能处理的远不止数值,还可以处理文本.图形.音频.视频.网页等各种各样的数据,不同 ...

  2. 记录我的 python 学习历程-Day03 数据类型 str切片 for循环

    一.啥是数据类型 ​ 我们人类可以很容易的分清数字与字符的区别,但是计算机并不能呀,计算机虽然很强大,但从某种角度上看又很傻,除非你明确的告诉它,1是数字,"汉"是文字,否则它是分 ...

  3. python学习第九天数据类型列表创建,查找操作方法

    数据类型中列表是整个python最常用的数据类型,列表最常用的方法就是创建,增删改查,切片,循环以及排序等系列操作,任何操作都离不开增删改查操作,这样很容记住操作方法 1,列表的创建 list=[] ...

  4. Python学习手册之数据类型

    在上一篇文章中,我们介绍了 Python 的异常和文件,现在我们介绍 Python 中的数据类型. 查看上一篇文章请点击:https://www.cnblogs.com/dustman/p/99799 ...

  5. Python学习-字符编码, 数据类型

    本篇主要内容: 字符编码 Python中的数据类型有哪些 类型的一些常用操作及方法 一.字符编码 编码解释的大部分内容摘自廖雪峰老师教程中的讲解,点击跳转. 简单介绍: 我们知道计算机只能处理数字,如 ...

  6. python学习之核心数据类型

    python核心数据类型 对象类型 例子 数字 1234,-345 字符串 'spam' 列表 [1,3,'ds'] 元组 (1,'spam',6) 字典 {'name':'lili','age':1 ...

  7. python学习03-数据类型

    一.基本数据类型--数字 布尔型 bool型只有两个值:True和False 之所以将bool值归类为数字,是因为我们也习惯用1表示True,0表示False. 以下是布尔值是False的各种情况: ...

  8. python学习之基本数据类型

    python的基本数据类型有数字.字符串.列表.字典.元祖.布尔值 一.数字 1.1.字符转换为数字 实例: a=" b=int(a) print(b+) 运行结果: 可以用type查看数据 ...

  9. Python学习笔记3_数据类型

    Python数据类型:数字.字符串.列表.元祖.字典 一.数字类型:(整型.长整型.浮点型.复数型) 1.整型(int):表示范围-2,147,483,648到2,147,483,647 2.长整型( ...

  10. 02 Python学习笔记-基本数据类型(二)

    一.基本知识 1.缩进: 2.一行多条语句: 3.断行: 4.注释 # 单行注释 '''这是一段 多行注释''' 5. 变量 1. 变量类型(局部变量.全局变量.系统变量) 2. 变量赋值 多重赋值x ...

随机推荐

  1. MySQL MyISAM引擎转换为InnoDB操作记录

    进入mysql命令行模式: # mysql -uroot -ppwd 1.查看mysql提供什么存储引擎: mysql> show engines; 2.查看mysql当前提供的默认存储引擎: ...

  2. ebs 12.1.1 单节点多用户安装

    本次测试环境:操作系统 oracle linux 6.9   oracle ebs 12.1.1   192.168.20.210  erpapp1.hthorizon.com erpapp1 yum ...

  3. hadoop生态系统主要架构图汇总

    1 hadoop1.0时期架构 2 hadoop2.0时期架构 3 hdfs架构 [Active Namenode]:主 Master(只有一个),管理 HDFS 的名称空间,管理数据块映射信息:配置 ...

  4. vue.js computed,watch的区别

    computed: 当数据没有变化时,它会去读取缓存,当数据有变化时,它才会去执行computed,而不会像method和watch一样每次都去执行函数(摘自https://www.jb51.net/ ...

  5. [正则表达式]匹配Unicode

    一.PHP[PCRE]之Unicode PCRE支持的16进制字符编码转义符有 \x00-\xFF,或\x{num},num为任意位16进制数 但并不支持\u0000-\uFFFF这的形式 PCRE运 ...

  6. winform生成条形码和二维码(ZXing.Net)

    首先在项目添加ZXing.Net. 工具-->Nuget包管理器-->Nuget程序包  在所搜栏输入 ZXing.Net 如下图: 添加完成后会看见: 效果图: 所有代码: /// &l ...

  7. Confluence 6 如何备份和恢复

    如何备份 有关备份你数据库使用的命令与你使用的具体数据库有关,例如针对 PostgreSQL 数据库,备份命令为 pg_dump dbname > outfile. 你应该针对你使用的数据库不同 ...

  8. 电子书转换为PDF格式

    目录 一.mobi 转换 pdf 步骤 二.查看转换后的结果目录 三.将PDF还原文件名且移出至新目录 背景:当我们从网上下载一些电子小说或书籍的时候,一般文件的格式可能是.epub..mobi等.这 ...

  9. java Swing组件和事件处理

    1.常见的容器 JComponent是 Container 的子类,中间容器必须添加到底层容器中才能够发挥作用, JPanel 面板 :使用jPanel 创建一个面板,再通过添加组件到该面板上面,JP ...

  10. jquery checkbox勾选/取消勾选只能操作一次的诡异问题

    第一次执行,没问题,但第二次执行就有问题了,选择不了 解决办法:把attr()换成prop() $("#CheckedAll").click(function () { if ($ ...