Python learning (start and end) Chapter 2 lists, tuples, dictionaries and sets

chapter 2

2.1 Lists and tuples (the other two sequence structures in python besides strings)

  • The elements in the list are mutable, and the elements in the tuple are immutable

2.1.1 List

  • Use [] or list() to create a list
    • Allow the same elements
    • The list consists of 1 or more elements
    • Suitable for positioning an element using sequence and position
list1 = []
list1 = ['monday','huang','1','1','铭']
empty_list = list() #创建空列表
  • Use list() to convert other data types into lists
    • The string is converted to a list of single letters
    >>>list('cat')
    ['c','a','t']
    
    • Convert tuples to lists
    >>>a_tuple = ('huang','jian','ming')
    >>>list(a_tuple)
    ['huang','jian','ming']
    
  • Specify range and use slice to extract elements
    • Slice extraction
    >>>marxes = ['huang','jian','ming']
    >>>marxes[0:2]
    ['huang','jian']
    >>>marxes[::2]
    ['huang','ming']
    >>>marxes[::-2]
    ['ming','huang']
    #巧妙实现列表逆序
    >>>marxes[::-1]
    ['ming','jian','huang']
    
  • List operation
    • list.append() adds elements to the end
    a_list.append('a_str')
    
    • list.extend() or += merge list
    list1.extend(list2)
    list1 += list2
    
    • list.insert() inserts an element at the specified position
    #insert()可在列表任意指定位置插入元素,其中若偏移量超过了尾部,则会默认插入到列表最后
    >>>a_list = ['huang','jian','ming']
    >>>a_list.insert(1,'huang')
    ['huang','huang','jian','ming']
    
    • del deletes the element at the specified position
    >>>del a_list[-3]
    ['huang','jian','ming']
    
    • list.remove() removes elements with specified values
    a_list.remove('huang')
    
    • list.pop() Get and delete the element at the specified position
    #pop(0)返回列表头元素并删除,pop()或pop(-1)返回列表尾元素并删除
    >>>a_list.pop(1)
    'ming'
    >>>a_list
    ['jian']
    
    • list.index() Query the position of an element with a specific value
    >>>a_list.index('huang')
    0
    
    • Use in to determine whether the value exists
    >>>'huang' in a_list
    True
    #同一个值可能出现在列表多个位置,但至少出现一次,in就会返回True
    
    • list.count() records the number of occurrences of a specific value
    >>>a_list = ['huang','huang','jian','ming']
    >>>a_list.count('huang')
    2
    
    • Rearrange elements
      • list.sort(reverse=True/False) will sort the original list and change the content of the original list
      • The general function sorted() will return a sorted copy of the list, with the original list content unchanged
      • The numeric elements will be sorted in ascending order from smallest to largest by default, and the string will be sorted in alphabetical order (can be converted by reverse=True/False)
    • list2 = list1.copy()
      • Using = assignment is different from list.copy(), the change after assignment will affect the original list, copy will not

2.1.2 Tuples (tuple tuples are immutable, once defined, they cannot be added, deleted, modified, checked, etc.)

  • Create a tuple with ()
#空元组
>>>empty_tuple = ()
()
>>>one_tuple = 'huang',
('huang',)
>>>marx_tuple = 'huang','jian'
('huang','jian')
  • Tuple unpacking
>>>a_tuple = 'huang','jian','ming' >>>a,b,c = a_tuple
>>>a
'huang'
>>>b
'jian'
>>>c
'ming'

2.1.3 Dictionary (dict)

  • Similar to a list, but the order of the elements does not matter, access is through the key of the key-value pair
  • The key can be a string and any other immutable type in python (boolean, integer, floating point, tuple, string, etc.)
  • Create a dictionary
#空字典
>>>empty_dict = {
    
    }
>>>a_dict = {
    
    'name':'hjm','age':24}
#用dict()将包含双值子序列的序列转换成字典
>>>lol = [['name','hjm'],['age','24']]
>>>dict(lol)
{
    
    'name':'hjm','age':'24'}
#包含双值元组的列表
>>>lot = [('a','b'),('c','d')]
>>>dict(lot)
{
    
    'a':'b','c':'d'}
#包含双值列表的元组
>>>tol = (['name','hjm'],['age','24'])
>>>dict(tol)
{
    
    'name':'hjm','age':'24'}
#双字符的字符串组成的列表
>>>los = ['ab','cd','ef']
>>>dict(los)
{
    
    'a':'b','c':'d','e':'f'}
  • Use [key] to add or modify elements
#若字典中没有对应的key,则向字典中添加该键值对
>>>a_dict = {
    
    'name':'hjm'}
>>>a_dict['age'] = '24'
{
    
    'name':'hjm','age':'24'}
  • Use dict1.update(dict2) to merge dictionaries
>>>pythons = {
    
    
    'name1':'h1',
    'name2':'h2',
    'name3':'h3'
}
>>>others = {
    
    
    'age1':'m1',
    'age2':'m2'
    'name1':'m1'
}
>>>pythons.update(others)
>>>pythons
# 注意此处相同的键,对应的值会覆盖掉pyhtons中对应的值
{
    
    'name1':'m1','name2':'h2','name3':'h3','age1':'m1','age2':'m2'}
  • del deletes the element with the specified key
>>>del pythons['age2']
{
    
    'name1':'m1','name2':'h2','name3':'h3','age1':'m1'}
  • dict.clear() clear all elements
  • Use in to determine whether a key exists in a dictionary
>>>'name' in a_dict  
True/False
  • Use dict.keys() to get all keys
>>>customers = {
    
    'h':12,'j':23,'m':45}
>>>customers.keys()
dict_keys(['h','j','m'])
>>>list(customers.keys())  
['h','j','m']
  • Use dict.values() to get all values
>>>customers.values()
dict_values([12, 23, 45])
  • Use dict.items() to get all key-value pairs
>>>customers.items()  
dict_items([('h', 12), ('j', 23), ('m', 45)])
  • Also use = assignment, modification will affect the original dictionary, using dict.copy() will not affect the original dictionary

2.1.4 Collection

  • Use set() to create a collection
#创建空集
>>>empty_set = set()  
set() #空集,{}表示空字典
>>>a_set = {
    
    0,2,4,6,8}
{
    
    0,4,2,6,8}
#与字典的键一样,集合是无序的
  • Use set() to convert other types to sets
#重复的值将被丢弃
#包含重复字母的字符串
>>>set('letters')
{
    
    'l','e','t','r','s'}
#转换列表为集合  
>>>set(['huang','jian','ming'])  
{
    
    'huang','jian','ming'}  
#元组转换为集合
>>>set(('huang','jian','ming'))  
{
    
    'huang','jian','ming'}  
#当字典作为参数进行转换时,只有键会被使用
>>>set({
    
    'name':'hjm','sex':'man','stature':174})
{
    
    'name','sex','stature'}
  • Use in to test whether the value exists
>>>drinks = {
    
    
    'martini':{
    
    'vodka','vermouth'},
    'black russian':{
    
    'vodka','kahlua'},
    'white russian':{
    
    'cream','kahlua','vodka'},
    'manhattan':{
    
    'rye','vermouth','bitters'},
    'screwdriver':{
    
    'orange juice','vodka'}
}
#分别提取字典中的键和值
>>>for name,contents in drinks.items():
    if 'vodka' in contents:
        print(name)

screwdriver
martini
black russian
white russian

>>>for name,content in drinks.items():
    if 'vodka' in content and not ('vermouth' in content or 'cream' in content):
        print(name)

screwdriver
black russian
  • Common set operations
    • Use & or set1.intersection(set2) to get the intersection of sets
    • Use | or set1.union(set2) to get the union of the set (at least one element in the set appears)
    • Use-or set1.difference(set2) to get the difference of two sets (appears in the first set but not in the second set)
  • Very use of set set operations
    • Use ^ or set1.symmetric_difference(set2) to get the exclusive OR set of two sets (only once in two sets)
    • Use <= or set1.issubset(set2) to determine whether a set is a subset of another set (all elements of the first set appear in the second set)
    • Use >= or issuperset() to determine whether it is a superset
    • Use <or> to judge the true subset

Guess you like

Origin blog.csdn.net/Han_Panda/article/details/111301382