CSIC_716_20191106【列表、元组、字典、集合】

python的数据类型及其内置方法

一、列表(续)

list.count( )、list.index( )

list = ['1', '2', '3', '2', 'a', 'b', 'c', 'a']
print(list.count('a'))  # 用于统计某个元素的个数
print(list.index('a', 4, ))  # 查指定字符的第一个索引位置,如果查不到就会报错,查找范围可以指定

切片https://www.jianshu.com/p/15715d6f4dad

list.sort( )  、sorted(list) 

区别:sorted(list)排完之后会生成新的列表,list.sort( )是在原列表操作。

list2=[1, 4, 3, 5, 7]
list2.sort(reverse=True)  # 若reverse参数不写,默认为False,按照ASCII码从小到大排
print(list2)  # [7, 5, 4, 3, 1]

list3=[1, 4, 3, 5, 7]
print(sorted(list3, reverse=True))  # [7, 5, 4, 3, 1]
print(list3)  # [1, 4, 3, 5, 7]

list.clear( ) 清除

list4 = [1, 4, 3, 5, 7]
list4.clear()
print(list4)  # []

list.reverse( ) 反转排序

list4 = [1, 4, 3, 5, 7]
list4.reverse()
print(list4)  # [7, 5, 3, 4, 1]

Note that items in the sequence s are not copied; they are referenced multiple times. This often haunts new Python programmers; consider:

>>>
>>> lists = [[]] * 3
>>> lists
[[], [], []]
>>> lists[0].append(3)
>>> lists
[[3], [3], [3]]

What has happened is that [[]] is a one-element list containing an empty list, so all three elements of [[]] 3 are references to this single empty list. Modifying any of the elements of lists modifies this single list. You can create a list of different lists this way:

>>>
>>> lists = [[] for i in range(3)]
>>> lists[0].append(3)
>>> lists[1].append(5)
>>> lists[2].append(7)
>>> lists
[[3], [5], [7]]

二、元组 tuple

定义:通过小括号存储数据,数据间通过逗号分隔,元组的值不允许改变。

元组可以通过索引取值

tuple = (1, 2, 3)
print(tuple[0])  # 1

 索引切片   (取头不取尾)

tuple = (1, 2, 3)
print(tuple[0:1])  # (1,) 

  注意:如果元组中只有一个元素,一定要在末尾打上逗号,否则会默认为字符串

tuple2 = (1)
tuple3 = (1,)
print(type(tuple2))  # <class 'int'>
print(type(tuple3))  # <class 'tuple'>

   成员运算   in  ;not in

tuple = (1, 2, 3)
print( 1 not in tuple)  # False

 len( )  元素的个数

tuple = (1, 2, 3)
print(len(tuple))  # 3

 元组的自带方法  tuple.count( )、tuple.index( )

tuple = ('1', '2', '3', '2', 'a', 'b', 'c', 'a')
print(tuple.count('a'))  # 2
print(tuple.index('a'))  # 4
print(tuple.index('a', 5,))  # 7

 

总结:元组  有序的,不可变的,存多个值

三、字典

字典的定义有三种方式:

'''
字典的三种定义方式
'''
dict1 = {'name': 'abc', 'age': 16}
print(dict1)  # {'name': 'abc', 'age': 16}
dict2 = dict({'name': 'abc', 'age': 16})
print(dict2)  # {'name': 'abc', 'age': 16}
list1 = ['name', 'age']
list2 = ['abc', 16]
dict4 = zip(list1, list2)
for j in dict4:
    print(j, type(j), end=' ',)  #('name', 'abc') <class 'tuple'> ('age', 16) <class 'tuple'>
print()
dict5 = dict(zip(list1, list2))  # 通过dict()将zip类型转换成dict类型
print(dict5)  # {'name': 'abc', 'age': 16}

dict.get(  )

'''
get 方法
'''
dict1 = {'name': 'abc', 'age': 16}
print(dict1.get('name'))  # abc
print(dict1.get('name','789'))  # abc
print(dict1.get('gender', 'male'))  # male

dict.get( )的使用场景:

将get的第一个参数做成用户界面传入的变量,当成dict的key,第二个参数做成错误提示。如果传入的变量不是dict的key,则会输出错误提示。

dict.setdefault( )

注意setdefault(  )和get(  )的区别

'''
get 方法
setdefault方法
辨析
'''
dict1 = { }
print(dict1.get('name'))  # None ()默认值
print(dict1)  # { }
print(dict1.get('name', 'abc'))  # abc
print(dict1)  # { }

dict2 = { }
print(dict2.setdefault('name'))  # None ()默认值
print(dict2)  # {'name': None}
print(dict2.setdefault('name', 'abc'))  # None
print(dict2)  # {'name': None}
print(dict2.setdefault('gender', 'male'))  # male
print(dict2)  # {'name': None, 'gender': 'male'}

总结:

使用dict.get( )方法,对dict不会造成任何影响。

如果get中的第一个参数key在dict中,则返回dict中的value,否则返回get方法的第二个参数,如果没有参数,则返回默认值None

使用dict.getdefault( )方法,对dict会造成影响。

如果setdefault中的第一个参数key在dict中,则返回dict中的value;否则返回getdefault方法的第二个参数,如果没有参数,则返回None同时,将key和第二个参数(默认None)以键值对形式存入dict;

dict.keys( ) 、dict.values( ) 、dict.items( )

'''
dict.keys() 取所有的key
dict.values()  取所有的value
dict.items()  取所有的键值对
'''
dict1 = {'name': 'abc', 'age': 16}
print(dict1.keys())  # dict_keys(['name', 'age'])
for key in dict1.keys():
    print(key, end=' ')  # name age

print(dict1.values())  # dict_values(['abc', 16])
for value in dict1.values():
    print(value, end=' ')  # abc 16

print(dict1.items())  # dict_items([('name', 'abc'), ('age', 16)])
for key, value in dict1.items():
    print(key, value, end=' ')  # name abc age 16 

  

dict.pop( key )

指定key进行删除,dict.pop( key ) 的返回值为该key对应的value

dict.popitem( )

随机删除一个键值对,dict.popitem( ) 的返回值为被删除的键值对,返回值的类型为tuple元组

dict1.update( dict2 )

'''
dict1.update( dict2)
用dict2来更新dict1
简言之,向dict1的序列中插dict2,key相同则更新value,无则增加key-value。
'''
dict1 = {'name': 'abc', 'age': 16}
dict2 = {'name': 'zhang'}
dict3 = {'gender': 'femal'}
dict3.update(dict1)
print(dict3)  # {'gender': 'femal', 'name': 'abc', 'age': 16}
dict1.update(dict2)
print(dict1)  # {'name': 'zhang', 'age': 16}

  

dict.fromkeys( parameter1parameter2)     parameter1必须是可迭代对象

通过fromkeys生成的字典,keyparameter1中的各个元素,所有的value全部为parameter2

dict1 = dict.fromkeys(range(3), 'csic')
print(dict1)  # {0: 'csic', 1: 'csic', 2: 'csic'}

  

总结   字典 无序的,可变的,存多个值

四、集合

集合的用途是去重关系运算

集合通过大括号存储,每个元素以逗号分隔,

定义空集合时,必须使用set( )方式

ss1 = set(range(3))  # set()的参数必须是可迭代对象,或者为空
print(ss1)  # {0, 1, 2}
print(type(ss1))  # <class 'set'>

集合里面不能存重复的元素

ss2 = {1, 2, 3, 1, 2, 1, 3}
print(len(ss2))  # 3
print(ss2)  # {1, 2, 3}

 

总结

set集合是无须的,存多个值,可变的,集合的可变仅限于增加和删除,不能对集合现有的元素进行修改。

frozenset是冻结的集合,它是不可变的,存在哈希值,好处是它可以作为字典的key,也可以作为其它集合的元素。一旦创建便不能更改,没有add,remove方法。

原文地址:https://www.cnblogs.com/csic716/p/11806807.html