基本数据类型
2020-08-21 14:56:00   0  举报             
     
         
 AI智能生成
  Python 基本数据类型及操作方法
    作者其他创作
 大纲/内容
  数字(Number)    
     加  +
减 -
乘 *
除 /
取整 //
幂 **
取余 %
    减 -
乘 *
除 /
取整 //
幂 **
取余 %
 包含:
整数(int)
浮点数(fioat)
复数(complex)
    整数(int)
浮点数(fioat)
复数(complex)
 数学函数    
     abs(x):返回数字的绝对值,如abs(-10) 返回 10  
     ceil(x):返回数字的上入整数,如math.ceil(4.1) 返回 5  
     exp(x):返回e的x次幂(ex),如math.exp(1) 返回2.718281828459045  
     fabs(x):返回数字的绝对值,如math.fabs(-10) 返回10.0  
     floor(x):返回数字的下舍整数,如math.floor(4.9)返回 4  
     log(x):如math.log(math.e)返回1.0,math.log(100,10)返回2.0  
     log10(x):返回以10为基数的x的对数,如math.log10(100)返回 2.0  
     max(x1, x2,...):返回给定参数的最大值,参数可以为序列。  
     min(x1, x2,...):返回给定参数的最小值,参数可以为序列。  
     modf(x):返回x的整数部分与小数部分,两部分的数值符号与x相同,整数部分以浮点型表示。  
     pow(x, y):x**y 运算后的值。  
     round(x [,n]):返回浮点数 x 的四舍五入值,如给出 n 值,则代表舍入到小数点后的位数。
其实准确的说是保留值将保留到离上一位更近的一端。
    其实准确的说是保留值将保留到离上一位更近的一端。
 sqrt(x):返回数字x的平方根。  
     元祖(tuple)    
     创建空元组: tup1 = ()  
     修改元祖:元祖一旦初识创建,无法修改    
     tup1 = (12, 34.56)
tup2 = ('abc', 'xyz')
 
# 以下修改元组元素操作是非法的。
# tup1[0] = 100
 
# 创建一个新的元组
tup3 = tup1 + tup2
print (tup3)
(12, 34.56, 'abc', 'xyz')
  
    tup2 = ('abc', 'xyz')
# 以下修改元组元素操作是非法的。
# tup1[0] = 100
# 创建一个新的元组
tup3 = tup1 + tup2
print (tup3)
(12, 34.56, 'abc', 'xyz')
 集合(set)    
     集合(set)是一个无序的不重复元素序列。
可以使用大括号 { } 或者 set() 函数创建集合,注意:创建一个空集合必须用 set() 而不是 { },因为 { } 是用来创建一个空字典。
    可以使用大括号 { } 或者 set() 函数创建集合,注意:创建一个空集合必须用 set() 而不是 { },因为 { } 是用来创建一个空字典。
 内置方法    
     add():为集合添加元素    
     fruits = {"apple", "banana", "cherry"}
fruits.add("orange")
print(fruits)
{'apple', 'banana', 'orange', 'cherry'}
  
    fruits.add("orange")
print(fruits)
{'apple', 'banana', 'orange', 'cherry'}
 clear():移除集合中的所有元素    
     fruits = {"apple", "banana", "cherry"}
fruits.clear()
print(fruits)
set()
  
    fruits.clear()
print(fruits)
set()
 copy():拷贝一个集合    
     fruits = {"apple", "banana", "cherry"}
x = fruits.copy()
print(x)
{'cherry', 'banana', 'apple'}
  
    x = fruits.copy()
print(x)
{'cherry', 'banana', 'apple'}
 difference():返回多个集合的差集    
     x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
 
z = x.difference(y)
 
print(z)
{'cherry', 'banana'}
  
    y = {"google", "microsoft", "apple"}
z = x.difference(y)
print(z)
{'cherry', 'banana'}
 difference_update():移除集合中的元素,该元素在指定的集合也存在。    
     x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
 
x.difference_update(y)
 
print(x)
{'cherry', 'banana'}
  
    y = {"google", "microsoft", "apple"}
x.difference_update(y)
print(x)
{'cherry', 'banana'}
 discard():删除集合中指定的元素    
     fruits = {"apple", "banana", "cherry"}
 
fruits.discard("banana")
 
print(fruits)
{'cherry', 'apple'}
  
    fruits.discard("banana")
print(fruits)
{'cherry', 'apple'}
 intersection():返回集合的交集    
     x = {"apple", "banana", "cherry"}
y = {"google", "runoob", "apple"}
z = x.intersection(y)
 
print(z)
{'apple'}
  
    y = {"google", "runoob", "apple"}
z = x.intersection(y)
print(z)
{'apple'}
 intersection_update():返回集合的交集。    
     x = {"apple", "banana", "cherry"}
y = {"google", "runoob", "apple"}
 
x.intersection_update(y)
 
print(x)
{'apple'}
  
    y = {"google", "runoob", "apple"}
x.intersection_update(y)
print(x)
{'apple'}
 isdisjoint():判断两个集合是否包含相同的元素,如果没有返回 True,否则返回 False。    
     x = {"apple", "banana", "cherry"}
y = {"google", "runoob", "facebook"}
z = x.isdisjoint(y)
 
print(z)
True
  
    y = {"google", "runoob", "facebook"}
z = x.isdisjoint(y)
print(z)
True
 issubset():判断指定集合是否为该方法参数集合的子集。    
     x = {"a", "b", "c"}
y = {"f", "e", "d", "c", "b", "a"}
z = x.issubset(y)
 
print(z)
    y = {"f", "e", "d", "c", "b", "a"}
z = x.issubset(y)
print(z)
 issuperset():判断该方法的参数集合是否为指定集合的子集    
     x = {"f", "e", "d", "c", "b", "a"}
y = {"a", "b", "c"}
 
z = x.issuperset(y)
 
print(z)
True
  
    y = {"a", "b", "c"}
z = x.issuperset(y)
print(z)
True
 pop():随机移除元素    
     fruits = {"apple", "banana", "cherry"}
 
fruits.pop()
 
print(fruits)
{'apple', 'banana'}
  
    fruits.pop()
print(fruits)
{'apple', 'banana'}
 remove():移除指定元素    
     fruits = {"apple", "banana", "cherry"}
 
fruits.remove("banana")
 
print(fruits)
{'cherry', 'apple'}
  
    fruits.remove("banana")
print(fruits)
{'cherry', 'apple'}
 symmetric_difference():返回两个集合中不重复的元素集合。    
     x = {"apple", "banana", "cherry"}
y = {"google", "runoob", "apple"}
 
z = x.symmetric_difference(y)
 
print(z)
{'google', 'cherry', 'banana', 'runoob'}
  
    y = {"google", "runoob", "apple"}
z = x.symmetric_difference(y)
print(z)
{'google', 'cherry', 'banana', 'runoob'}
 symmetric_difference_update():移除当前集合中在另外一个指定集合相同的元素,并将另外一个指定集合中不同的元素插入到当前集合中。    
     x = {"apple", "banana", "cherry"}
y = {"google", "runoob", "apple"}
 
x.symmetric_difference_update(y)
 
print(x)
{'google', 'cherry', 'banana', 'runoob'}
  
    y = {"google", "runoob", "apple"}
x.symmetric_difference_update(y)
print(x)
{'google', 'cherry', 'banana', 'runoob'}
 union():返回两个集合的并集    
     x = {"apple", "banana", "cherry"}
y = {"google", "runoob", "apple"}
 
z = x.union(y)
 
print(z)
{'cherry', 'runoob', 'google', 'banana', 'apple'}
  
    y = {"google", "runoob", "apple"}
z = x.union(y)
print(z)
{'cherry', 'runoob', 'google', 'banana', 'apple'}
 update():给集合添加元素    
     x = {"apple", "banana", "cherry"}
y = {"google", "runoob", "apple"}
 
x.update(y)
 
print(x)
{'banana', 'apple', 'google', 'runoob', 'cherry'}
  
    y = {"google", "runoob", "apple"}
x.update(y)
print(x)
{'banana', 'apple', 'google', 'runoob', 'cherry'}
 集合的运算    
     交集(&)    
     s = {1,2,3,4,5}
s2 = {3,4,5,6,7}
result = s & s2 # {3, 4, 5}
  
    s2 = {3,4,5,6,7}
result = s & s2 # {3, 4, 5}
 并集(|)    
     s = {1,2,3,4,5}
s2 = {3,4,5,6,7}
result = s | s2 # {1,2,3,4,5,6,7}
  
    s2 = {3,4,5,6,7}
result = s | s2 # {1,2,3,4,5,6,7}
 叉集(-)    
     s = {1,2,3,4,5}
s2 = {3,4,5,6,7}
result = s - s2 # {1, 2}
  
    s2 = {3,4,5,6,7}
result = s - s2 # {1, 2}
 异或集(ˆ)    
     s = {1,2,3,4,5}
s2 = {3,4,5,6,7}
result = s ^ s2 # {1, 2, 6, 7}
  
    s2 = {3,4,5,6,7}
result = s ^ s2 # {1, 2, 6, 7}
 子集(<=)
真子集(<)
    真子集(<)
 a = {1,2,3}
b = {1,2,3,4,5}
result = a <= b # True
result = {1,2,3} <= {1,2,3} # True
result = {1,2,3,4,5} <= {1,2,3} # False
result = {1,2,3} < {1,2,3} # False
result = {1,2,3} < {1,2,3,4,5} # True
  
    b = {1,2,3,4,5}
result = a <= b # True
result = {1,2,3} <= {1,2,3} # True
result = {1,2,3,4,5} <= {1,2,3} # False
result = {1,2,3} < {1,2,3} # False
result = {1,2,3} < {1,2,3,4,5} # True
 超集(>=)
真超集(>)
    真超集(>)
 子主题  
     字节(byte)  
     字符串(str)    
     索引:起始下标为0 (从前往后数),末尾下标为-1(从后往前数)    
     str_a = 'hello python'
print(str_a[0]) #打印结果:h
print(str_a[-1]) #打印结果:n
    print(str_a[0]) #打印结果:h
print(str_a[-1]) #打印结果:n
 切片:格式:[起始位置:终止位置:步长],默认的步长为1    
     str_a = 'hello python'
print(str_a[0:12:3]) #打印结果:hlph
    print(str_a[0:12:3]) #打印结果:hlph
 拼接:字符串有两种拼接方法,
第一种:str1+str2
第二种:','.join((str1,str2)),join方法内的参数是一个可迭代类型的数据
    
    第一种:str1+str2
第二种:','.join((str1,str2)),join方法内的参数是一个可迭代类型的数据
 str_a = 'hello'
str_b = 'python'
print(str_a + str_b) #打印结果:hellopython
print(','.join((str_a, str_b))) #打印结果:hello,python
  
    str_b = 'python'
print(str_a + str_b) #打印结果:hellopython
print(','.join((str_a, str_b))) #打印结果:hello,python
 内置方法    
     capitalize() :首字母大写    
     >>> a='Hello World'
>>> print(a.capitalize())
Hello world
    >>> print(a.capitalize())
Hello world
 center():将字符串放入中心位置可指定长度以及位置两边字符    
     str.center()
>>> a='hello world'
>>> print(a.center(40,'*'))
**************hello world***************
  
    >>> a='hello world'
>>> print(a.center(40,'*'))
**************hello world***************
 count():统计字符串片段在字符串中出现的次数,统计子串出现的次数,若不存在则返回0    
     str_a = '123abc456def456abc456'
res = str_a.count('456') #res的结果为3
    res = str_a.count('456') #res的结果为3
 casefold():把字符串全变小写    
     >> > c = 'Alex Li'
>> > c.casefold()
'alex li'
    >> > c.casefold()
'alex li'
 find(参数1,参数2):查找字符串片段在字符串中出现的起始下标位置,
参数1表示要查找的字串,参数2表示查找的起始位置,如果没有找到字串则返回-1
    
    参数1表示要查找的字串,参数2表示查找的起始位置,如果没有找到字串则返回-1
 str_a = '123abc456def' 
res = str_a.find('c', 3) #res的结果为5
    res = str_a.find('c', 3) #res的结果为5
 rfind(str, beg=0,end=len(string)):类似于 find()函数,不过是从右边开始查找    
     子主题  
     format(self, *args, **kwargs):格式化输出    
     >> > s = "Welcome {0} to Apeland,you are No.{1} user."
>> > s.format("Eva", 9999)
'Welcome Eva to Apeland,you are No.9999 user.'
>> > s1 = "Welcome {name} to Apeland,you are No.{user_num} user."
>> > s1.format(name="Alex", user_num=999)
'Welcome Alex to Apeland,you are No.999 user.'
    >> > s.format("Eva", 9999)
'Welcome Eva to Apeland,you are No.9999 user.'
>> > s1 = "Welcome {name} to Apeland,you are No.{user_num} user."
>> > s1.format(name="Alex", user_num=999)
'Welcome Alex to Apeland,you are No.999 user.'
 replace(参数1,参数2,参数3):替换指定的字符串片段,
参数1表示要替换的字符串片段,参数2表示替换之后的字符串片段,参数3指定替换的次数(默认为替换所有的)
    
    参数1表示要替换的字符串片段,参数2表示替换之后的字符串片段,参数3指定替换的次数(默认为替换所有的)
 str_a = '123abc456def456456'
res = str_a.replace('456', '789', 2) #res的结果为123abc789def789456
    res = str_a.replace('456', '789', 2) #res的结果为123abc789def789456
 split(参数1,参数2):指定分割点对字符串进行分割,
参数1表示分割点,参数2指定分割的次数(默认找到的所有分割点及您进行分割)
    
    参数1表示分割点,参数2指定分割的次数(默认找到的所有分割点及您进行分割)
 str_a = '123abc456def456abc456'
res = str_a.split('abc', 1) #res的结果为['123', '456def456abc456']
    res = str_a.split('abc', 1) #res的结果为['123', '456def456abc456']
 upper():将小写字母转为大写字母    
     str_a = '123aBc456DeF456Abc456'
res = str_a.upper() #res的结果为123ABC456DEF456ABC456
    res = str_a.upper() #res的结果为123ABC456DEF456ABC456
 lower():将大写字母转为小写字母    
     str_a = '123aBc456DeF456Abc456'
res = str_a.lower() #res的结果为123abc456def456abc456
    res = str_a.lower() #res的结果为123abc456def456abc456
 len():返回字符串的长度    
     >>>str = "runoob"
>>> len(str) # 字符串长度
6
    >>> len(str) # 字符串长度
6
 swapcase() :大小写互换    
     >>> a='Hello World'
>>> print(a.swapcase())
hELLO wORLD
    >>> print(a.swapcase())
hELLO wORLD
 strip():删除字符串两边的指定字符,括号的写入指定字符,默认为空格    
      a='   hello   '
b=a.strip()
print(b) # 'hello'
    b=a.strip()
print(b) # 'hello'
 rstrip():删除字符串右边的指定字符,括号的写入指定字符,默认空格    
     >>> a='   hello   '
>>> b=a.rstrip()
>>> print(b)
hello
    >>> b=a.rstrip()
>>> print(b)
hello
 lstrip():删除字符串左边的指定字符,括号的写入指定字符,默认空格    
     >>> a='     hello     '
>>> b=a.lstrip()
>>> print(b)
hello #右边空格可能看的不是很明显
    >>> b=a.lstrip()
>>> print(b)
hello #右边空格可能看的不是很明显
 join():连接2个字符串,可指定连接符号    
     li=["alex","eric"]
s="******".join(li)
print(s)
输出结果 alex******eric
    s="******".join(li)
print(s)
输出结果 alex******eric
 index():检测字符串中是否包含子字符串str,可指定范围,和find()一样,唯一不同点在于当找不到子串时,抛出ValueError错误。    
     子主题  
     字符串的测试、判断函数,这一类函数在string模块中没有,这些函数返回的都是bool值    
     1 S.startswith(prefix[,start[,end]])        # 是否以prefix开头 
2 S.endswith(suffix[,start[,end]]) # 以suffix结尾
3 S.isalnum() # 否全是字母和数字,并至少有一个字符
4 S.isalpha() # 是否全是字母,并至少有一个字符
5 S.isdigit() # 是否全是数字,并至少有一个字符
6 S.isspace() # 是否全是空白字符,并至少有一个字符
7 S.islower() # S中的字母是否全是小写
8 S.isupper() # S中的字母是否便是大写
9 S.istitle() # S是否是首字母大写的
10 S.isprintable() # 是否是可打印字符(例如制表符、换行符就不是可打印字符,但空格是)
11 S.isdecimal() # 检查字符串是否只包含十进制字符,如果是返回 true,否则返回 false。
    2 S.endswith(suffix[,start[,end]]) # 以suffix结尾
3 S.isalnum() # 否全是字母和数字,并至少有一个字符
4 S.isalpha() # 是否全是字母,并至少有一个字符
5 S.isdigit() # 是否全是数字,并至少有一个字符
6 S.isspace() # 是否全是空白字符,并至少有一个字符
7 S.islower() # S中的字母是否全是小写
8 S.isupper() # S中的字母是否便是大写
9 S.istitle() # S是否是首字母大写的
10 S.isprintable() # 是否是可打印字符(例如制表符、换行符就不是可打印字符,但空格是)
11 S.isdecimal() # 检查字符串是否只包含十进制字符,如果是返回 true,否则返回 false。
 partition():分割,前中后三部分    
     s="alex SB alex"
ret = s.partition('SB')
print(ret)
# 输出元组 ('alex ', 'SB', ' alex')
    ret = s.partition('SB')
print(ret)
# 输出元组 ('alex ', 'SB', ' alex')
 splitlines():根据换行执行分割    
     s="alex\nalec"
ret=s.splitlines()
print(ret)
# 输出结果 ['alex', 'alec']
    ret=s.splitlines()
print(ret)
# 输出结果 ['alex', 'alec']
 swapcase():大写变小写,小写变大写    
     s="alExAlec"
ret=s.swapcase()
print(ret)
# 输出结果 ALeXaLEC
    ret=s.swapcase()
print(ret)
# 输出结果 ALeXaLEC
 zfill():返回指定长度的字符串,原字符串右对齐,前面填充0    
     s="alEx Alec"
ret=s.zfill(11)
print(ret)
# 输出结果 00alEx Alec
    ret=s.zfill(11)
print(ret)
# 输出结果 00alEx Alec
 ljust(width[, fillchar]):使用fillchar填充在字符串S的右边,使得整体长度为width。如果不指定fillchar,则默认使用空格填充。    
     >>> print('xyz'.ljust(5,'_'))
xyz__
    xyz__
 rjust(width[, fillchar]):使用fillchar填充在字符串S的左边,使得整体长度为width。如果不指定fillchar,则默认使用空格填充。    
     >>> print('xyz'.rjust(5,'_'))
__xyz
    __xyz
 列表(list)    
     创建:直接创建  L = [ ]  
     内置方法    
     list.append(obj):在列表末尾添加新的对象    
     list1 = ['Google', 'Runoob', 'Taobao']
list1.append('Baidu')
print ("更新后的列表 : ", list1)
更新后的列表 : ['Google', 'Runoob', 'Taobao', 'Baidu']
  
    list1.append('Baidu')
print ("更新后的列表 : ", list1)
更新后的列表 : ['Google', 'Runoob', 'Taobao', 'Baidu']
 list.count(obj):统计某个元素在列表中出现的次数    
     aList = [123, 'Google', 'Runoob', 'Taobao', 123];
print ("123 元素个数 : ", aList.count(123))
print ("Runoob 元素个数 : ", aList.count('Runoob'))
123 元素个数 : 2
Runoob 元素个数 : 1
  
    print ("123 元素个数 : ", aList.count(123))
print ("Runoob 元素个数 : ", aList.count('Runoob'))
123 元素个数 : 2
Runoob 元素个数 : 1
 list.extend(seq):在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)    
     list1 = ['Google', 'Runoob', 'Taobao']
list2=list(range(5)) # 创建 0-4 的列表
list1.extend(list2) # 扩展列表
print ("扩展后的列表:", list1)
扩展后的列表: ['Google', 'Runoob', 'Taobao', 0, 1, 2, 3, 4]
  
    list2=list(range(5)) # 创建 0-4 的列表
list1.extend(list2) # 扩展列表
print ("扩展后的列表:", list1)
扩展后的列表: ['Google', 'Runoob', 'Taobao', 0, 1, 2, 3, 4]
 list.index(obj):从列表中找出某个值第一个匹配项的索引位置    
     list1 = ['Google', 'Runoob', 'Taobao']
print ('Runoob 索引值为', list1.index('Runoob'))
print ('Taobao 索引值为', list1.index('Taobao'))
Runoob 索引值为 1
Taobao 索引值为 2
  
    print ('Runoob 索引值为', list1.index('Runoob'))
print ('Taobao 索引值为', list1.index('Taobao'))
Runoob 索引值为 1
Taobao 索引值为 2
 list.insert(index, obj):将对象插入列表    
     list1 = ['Google', 'Runoob', 'Taobao']
list1.insert(1, 'Baidu')
print ('列表插入元素后为 : ', list1)
列表插入元素后为 : ['Google', 'Baidu', 'Runoob', 'Taobao']
  
    list1.insert(1, 'Baidu')
print ('列表插入元素后为 : ', list1)
列表插入元素后为 : ['Google', 'Baidu', 'Runoob', 'Taobao']
 list.pop([index=-1]):移除列表中的一个元素(默认最后一个元素),并且返回该元素的值    
     list1 = ['Google', 'Runoob', 'Taobao']
list1.pop()
print ("列表现在为 : ", list1)
list1.pop(1)
print ("列表现在为 : ", list1)
列表现在为 : ['Google', 'Runoob']
列表现在为 : ['Google']
  
    list1.pop()
print ("列表现在为 : ", list1)
list1.pop(1)
print ("列表现在为 : ", list1)
列表现在为 : ['Google', 'Runoob']
列表现在为 : ['Google']
 list.remove(obj):移除列表中某个值的第一个匹配项    
     子主题    
     list1 = ['Google', 'Runoob', 'Taobao', 'Baidu']
list1.remove('Taobao')
print ("列表现在为 : ", list1)
list1.remove('Baidu')
print ("列表现在为 : ", list1)
列表现在为 : ['Google', 'Runoob', 'Baidu']
列表现在为 : ['Google', 'Runoob']
  
    list1.remove('Taobao')
print ("列表现在为 : ", list1)
list1.remove('Baidu')
print ("列表现在为 : ", list1)
列表现在为 : ['Google', 'Runoob', 'Baidu']
列表现在为 : ['Google', 'Runoob']
 list.reverse():反向列表中元素    
     list1 = ['Google', 'Runoob', 'Taobao', 'Baidu']
list1.reverse()
print ("列表反转后: ", list1)
列表反转后: ['Baidu', 'Taobao', 'Runoob', 'Google']
  
    list1.reverse()
print ("列表反转后: ", list1)
列表反转后: ['Baidu', 'Taobao', 'Runoob', 'Google']
 list.sort( key=None, reverse=False):对原列表进行排序    
     aList = ['Google', 'Runoob', 'Taobao', 'Facebook']
 
aList.sort()
print ( "List : ", aList)
List : ['Facebook', 'Google', 'Runoob', 'Taobao']
  
    aList.sort()
print ( "List : ", aList)
List : ['Facebook', 'Google', 'Runoob', 'Taobao']
 list.clear():清空列表    
     list1 = ['Google', 'Runoob', 'Taobao', 'Baidu']
list1.clear()
print ("列表清空后 : ", list1)
列表清空后 : []
  
    list1.clear()
print ("列表清空后 : ", list1)
列表清空后 : []
 list.copy():复制列表    
     list1 = ['Google', 'Runoob', 'Taobao', 'Baidu']
list2 = list1.copy()
print ("list2 列表: ", list2)
list2 列表: ['Google', 'Runoob', 'Taobao', 'Baidu']
  
    list2 = list1.copy()
print ("list2 列表: ", list2)
list2 列表: ['Google', 'Runoob', 'Taobao', 'Baidu']
 列表的切片:同字符串  
     列表得嵌套    
     >>>a = ['a', 'b', 'c']
>>> n = [1, 2, 3]
>>> x = [a, n]
>>> x
[['a', 'b', 'c'], [1, 2, 3]]
>>> x[0]
['a', 'b', 'c']
>>> x[0][1]
'b'
    >>> n = [1, 2, 3]
>>> x = [a, n]
>>> x
[['a', 'b', 'c'], [1, 2, 3]]
>>> x[0]
['a', 'b', 'c']
>>> x[0][1]
'b'
 字典(dict)    
     字典的创建:键值对 
值可以取任何数据类型,但键必须是不可变的,如字符串,数字或元组。
    
    值可以取任何数据类型,但键必须是不可变的,如字符串,数字或元组。
 d = {key1 : value1, key2 : value2 }  
     内置方法    
     dict.clear():删除字典内所有元素    
     dict = {'Name': 'Zara', 'Age': 7};
print "Start Len : %d" % len(dict)
dict.clear()
print "End Len : %d" % len(dict)
Start Len : 2
End Len : 0
  
    print "Start Len : %d" % len(dict)
dict.clear()
print "End Len : %d" % len(dict)
Start Len : 2
End Len : 0
 dict.copy():返回一个字典的浅复制    
     dict1 = {'Name': 'Zara', 'Age': 7};
 
dict2 = dict1.copy()
print "New Dictinary : %s" % str(dict2)
New Dictinary : {'Age': 7, 'Name': 'Zara'}
  
    dict2 = dict1.copy()
print "New Dictinary : %s" % str(dict2)
New Dictinary : {'Age': 7, 'Name': 'Zara'}
 dict.fromkeys(seq[, val]):创建一个新字典,以序列 seq 中元素做字典的键,val 为字典所有键对应的初始值    
     seq = ('Google', 'Runoob', 'Taobao')
 
dict = dict.fromkeys(seq)
print "新字典为 : %s" % str(dict)
 
dict = dict.fromkeys(seq, 10)
print "新字典为 : %s" % str(dict)
新字典为 : {'Google': None, 'Taobao': None, 'Runoob': None}
新字典为 : {'Google': 10, 'Taobao': 10, 'Runoob': 10}
  
    dict = dict.fromkeys(seq)
print "新字典为 : %s" % str(dict)
dict = dict.fromkeys(seq, 10)
print "新字典为 : %s" % str(dict)
新字典为 : {'Google': None, 'Taobao': None, 'Runoob': None}
新字典为 : {'Google': 10, 'Taobao': 10, 'Runoob': 10}
 dict.get(key, default=None):返回指定键的值,如果值不在字典中返回default值    
     dict = {'Name': 'Runoob', 'Age': 27}
print "Value : %s" % dict.get('Age')
print "Value : %s" % dict.get('Sex', "Never")
Value : 27
Value : Never
  
    print "Value : %s" % dict.get('Age')
print "Value : %s" % dict.get('Sex', "Never")
Value : 27
Value : Never
 dict.has_key(key):如果键在字典dict里返回true,否则返回false    
     dict = {'Name': 'Zara', 'Age': 7}
print "Value : %s" % dict.has_key('Age')
print "Value : %s" % dict.has_key('Sex')
Value : True
Value : False
  
    print "Value : %s" % dict.has_key('Age')
print "Value : %s" % dict.has_key('Sex')
Value : True
Value : False
 dict.items():以列表返回可遍历的(键, 值) 元组数组    
     dict = {'Google': 'www.google.com', 'Runoob': 'www.runoob.com', 'taobao': 'www.taobao.com'}
 
print "字典值 : %s" % dict.items()
 
# 遍历字典列表
for key,values in dict.items():
print key,values
字典值 : [('Google', 'www.google.com'), ('taobao', 'www.taobao.com'), ('Runoob', 'www.runoob.com')]
Google www.google.com
taobao www.taobao.com
Runoob www.runoob.com
  
    print "字典值 : %s" % dict.items()
# 遍历字典列表
for key,values in dict.items():
print key,values
字典值 : [('Google', 'www.google.com'), ('taobao', 'www.taobao.com'), ('Runoob', 'www.runoob.com')]
Google www.google.com
taobao www.taobao.com
Runoob www.runoob.com
 dict.keys():以列表返回一个字典所有的键    
     dict = {'Name': 'Zara', 'Age': 7}
print "Value : %s" % dict.keys()
Value : ['Age', 'Name']
  
    print "Value : %s" % dict.keys()
Value : ['Age', 'Name']
 dict.setdefault(key, default=None):和get()类似, 但如果键不存在于字典中,将会添加键并将值设为default    
     dict = {'runoob': '菜鸟教程', 'google': 'Google 搜索'}
 
print "Value : %s" % dict.setdefault('runoob', None)
print "Value : %s" % dict.setdefault('Taobao', '淘宝')
Value : 菜鸟教程
Value : 淘宝
  
    print "Value : %s" % dict.setdefault('runoob', None)
print "Value : %s" % dict.setdefault('Taobao', '淘宝')
Value : 菜鸟教程
Value : 淘宝
 dict.update(dict2):把字典dict2的键/值对更新到dict里    
     dict = {'Name': 'Zara', 'Age': 7}
dict2 = {'Sex': 'female' }
dict.update(dict2)
print "Value : %s" % dict
Value : {'Age': 7, 'Name': 'Zara', 'Sex': 'female'}
  
    dict2 = {'Sex': 'female' }
dict.update(dict2)
print "Value : %s" % dict
Value : {'Age': 7, 'Name': 'Zara', 'Sex': 'female'}
 dict.values():以列表返回字典中的所有值    
     dict = {'Name': 'Zara', 'Age': 7}
print "Value : %s" % dict.values()
Value : [7, 'Zara']
  
    print "Value : %s" % dict.values()
Value : [7, 'Zara']
 pop(key[,default]):删除字典给定键 key 所对应的值,返回值为被删除的值。key值必须给出。 否则,返回default值。    
     site= {'name': '菜鸟教程', 'alexa': 10000, 'url': 'www.runoob.com'}
pop_obj=site.pop('name')
print pop_obj # 输出 :菜鸟教程
    pop_obj=site.pop('name')
print pop_obj # 输出 :菜鸟教程
 popitem():返回并删除字典中的最后一对键和值。    
     site= {'name': '菜鸟教程', 'alexa': 10000, 'url': 'www.runoob.com'}
pop_obj=site.popitem()
print(pop_obj)
print(site)
('url', 'www.runoob.com')
{'alexa': 10000, 'name': '\xe8\x8f\x9c\xe9\xb8\x9f\xe6\x95\x99\xe7\xa8\x8b'}
  
    pop_obj=site.popitem()
print(pop_obj)
print(site)
('url', 'www.runoob.com')
{'alexa': 10000, 'name': '\xe8\x8f\x9c\xe9\xb8\x9f\xe6\x95\x99\xe7\xa8\x8b'}
 布尔(boor)    
     两个值:True  、False  
     判定:为False :None、False、数字0、空列表[]、空字典{}、空元祖(),其余为True      (数字1为 True )  
     布尔运算    
     or    
     x or y :如果 x 是非 0,它返回 x 的值,否则它返回 y 的计算值。  
     and    
     x and y :如果 x 为 False,x and y 返回 False,否则它返回 y 的计算值。  
     not    
     not x :如果 x 为 True,返回 False 。如果 x 为 False,它返回 True。  
    
 
 
 
 
  0 条评论
 下一页