Sequence of Python (list & tuple & dictionary & set)

1. List

1. List: Stores information in groups, consisting of a series of elements in a specific order [most lists are dynamic]
[List names are generally plural, such as letters, cars, names
    Format: listName=[' ', /" "]  
    The index starts from 0 instead of 1, -1, -2... The index represents the first and second elements from the bottom, respectively]
1. Access list elements by index: ————————————–
{   cars=['玛莎拉蒂','凯迪拉克','劳斯莱斯']
    print(cars[0]) 
    玛莎拉蒂        }
2. Modify, add and delete elements ————————————
        ---修改:listName[索引值]="  "             //重新赋值
改变范围元素的值:listName[0:5]=[value,~/value]
             改表步长修改元素:listName[::2]=[~]    //步长为2
 ---添加:listName.append("元素名")   // [ə'pɛnd],附加
     空列表添:listName.append(“元素名”)
  ~~
【expend()   //扩展为序列】
            插入:listName.insert(索引值 ," ")     //必须指定索引和值
  listName[3:3]=[' ']
        ---删除: del listName[索引值]
                   . pop(索引值) //检索并删除,默认最后一个   //[pɑp], 取出
               remove("元素名"//存在重复的删除第一个值
  . clear() //清空列表
【都可根据切片删除 [ : ] 
pop() remove() 都为方法; del为语句】

========== Organize the list (adjust the order of elements) ===========

1. Temporary forward and reverse order (function: sorted( ))

print( sorted(listName) )
print( sorted(listName,reverse=True) )

2. Permanent positive and negative order (method: sort( ))

listName.sort()
listName.sort(reverse=True)
//listName.sort(key=lambda a:a[-1]) //sort by the last letter

3. Check the length of the list

len(listName)
[When an IndexError occurs, you can print the length/index value -1 to find out the logical error]

=================== Manipulate the list (do the same for each element) ===================

1. Traverse the list

cars=['Volkswagen','Mercedes','QQ']
for car in cars:
print(car) [variable singular, list name plural, ":" indented]
/for car in range(0,len(cars) ):
print(cars[car])
[Avoid indentation errors!

2. The function range(firstNum, finalNum) prints numbers

[Tips: Print from the first value to the end of the last value before the last index!

#####3. Create a list of values ​​(store a collection of numbers), and convert the function list() into a list
{
list( range(1,11) ) 


}
{
创建一个1-10的平方的数字列表
squares=[]
for value in range(1,11):
                  squares.append(value*value)
print(squares)  }
【 print(list('abc'))            //str转list
     print( list(('a','b','c')) )       //tuple转list 】

#####4.统计数字列表
min() /max() /sum()     //求列表中最小/最大/和值

#####5.列表解析 (将for循环和新建元素合并成一行,并自动附加新元素)1-10平方可以:
squares=[value*value for value in range(1,11)]
列表名=[表达式 循环给表达式提供值]
6. List slicing (using list part)

syntax: listName[start index: end index]
[Same as range(), no end value is taken! 】

players=['关羽','张飞','赵云','韩信','姜子牙']
print(players[2:4])【赵云 韩信 //Tips:对应元素为+1,当前4】
print(players[:3])
print(players[2:])
print(players[-2:])
}
A. Traverse the slice
print(newValue)
B. Copy the list
-newListName=listName[ : ]  //将整个列表切片赋值给newListName
-newListName=listName.copy()
            //listName2=listName1会造成共享引用

Replenish:

Repeat
listName*n //n means: number of prints
Detect the first position of an element
listName.index(elementName)

Count the number of occurrences of an element
print(listName.count(elementName))

2. Tuple (tuple)

1. Features
无序
不可变的序列
可包含任意对象的集合
下标访问
任意嵌套
不可变原位改变
2. Define a tuple
tupleName=(element_0,element_1)
3. Access a tuple
print(tupleName[0])
4. Access a specific range of elements by slicing
print(tupleName[:])
5. Cannot be modified or deleted
6. Define a tuple with only one element
one_tuple=("one",)  //需要加入一个“,”
7. Loop through tuples
for t in range(0,len(tupleName)):
    print(tupleName[t])
/for t in tupleName:
    print(t)
8. Tuple sorting
newTupleName=sorted(tupleName)
  //排序后,会返回一个新的list,元组本身不会变
#####9.列表转元组

tuple(listName)

#三、字典(dict)
#####1.含义
    动态结构(无序、可变)的一系列的-值对,每个键都和一个值相关联,可用使用键来访问相对应的值,将信息关联起来
    【Python不关心键值对的添加顺序,只关心键和值的关联关系】

#####2.格式:
<div>
    dict_name={
'key':'value',
~~
             }
</div>value:可为:数字、字符串、列表、字典;
    key值不能相同,后面的会覆盖掉前面的】

#####3.访问字典值
    dict_name['keyName']

#####4.添加键-值对
    dict_name['newKey']='newValue'

#####5.定义空字典
dict_name={}

#####6.修改字典中的值
```python
    dict_name['key']='newValue'
{//通过修改值判断外星人移动距离
alien_0={'x_position':0,'y_position':25,'speed':"medium"}
    #将外星人速度调为‘fast’
alien_0['speed']='fast'
记录外星人起始x轴位置
print("Original x-position:" + str(alien_0["x_position"]))
根据外星人速度决定移动多远
if alien_0['x_position']=='slow':
        x_increment=1
elif alien_0["speed"]=='medium':
        x_increment=2
else:
        x_increment=3
将新位置赋给变量
alien_0['x_position']=alien_0['x_position']+x_increment
print("New x_position is:"+str(alien_0['x_position']))  }




<div class="se-preview-section-delimiter"></div>
7. Delete key-value
del dict ['key']
//键-值永久删除了
8. Traverse the dictionary
A.遍历键-值对:
for key,value in dict_name.items():
//利用方法items()将变量key,value放到一个列表中,变量名应有意义!
//返回的为元组,访问元组中键/值:
for item in dict_name.items():
itemy[0/1] 
B.遍历键:
a.遍历所有键:   for key in dict_name.keys( ):
b.按顺序遍历键:for key in sorted(dict_name.keys( )):
c.遍历单个键:key_list=list(dict_name.keys())      key_list[]  
d.拿到每个键:key1,key2,key3,~=dict_name      print(key1,key2,key3,~)       //适用于键值对少的字典
C.遍历所有值:      for value in dict_name.values( ):
a.为值去重:       for value in set(dict_name.values()):
b.通过value找key:      value_list=list(dict_name.values())
     result=key_list[ value_list.index[ "~" ] ]
#####7.删除键-值
    del dict ['key']
    //键-值永久删除了

#####8.遍历字典
    A.遍历键-值对:
```python
for key,value in dict_name.items():
//利用方法items()将变量key,value放到一个列表中,变量名应有意义!
//返回的为元组,访问元组中键/值:
for item in dict_name.items():
itemy[0/1] 
B.遍历键:
a.遍历所有键:   for key in dict_name.keys( ):
b.按顺序遍历键:for key in sorted(dict_name.keys( )):
c.遍历单个键:key_list=list(dict_name.keys())      key_list[]  
d.拿到每个键:key1,key2,key3,~=dict_name      print(key1,key2,key3,~)       //适用于键值对少的字典
C.遍历所有值:      for value in dict_name.values( ):
a.为值去重:       for value in set(dict_name.values()):
b.通过value找key:      value_list=list(dict_name.values())
     result=key_list[ value_list.index[ "~" ] ]
9. Empty the dictionary

dicName.clear()

10. Nesting

A. Dictionary list: (alien list)
dicName1={'key1':"'value1',~}
dicName2={'key1':"'value2',~}
listName=[dicName1, dicName2] B.List
dictionary : (describe each pizza ingredient)
dicName={
'listName':[' ',' ']
}
for l_N in dicName['listName']: //traverse the specified list in the dictionary
/for key,value in dicName.items( ): //
for v in value: // Traverse the entire list dictionary
C. Dictionary dictionary: (stores user information)
dicName1={
'dicName2':{'key','value'},
}

Four, set (set)

1. Features

Mutable sequence, support in-situ changes
Can contain any type
Arbitrary nesting
No duplicate objects are allowed (automatic deduplication)

2. Format

name_set{ ‘set_0’,’set_1’,’set_2’ }

3. Collection deduplication//Using collection features

– deduplicate list
id_list = ['id_0','id_1','id_2','id_3']
id_set = set(id_list)
– deduplicate string
string_set = set("hello")

4. Create an empty collection

none_set = set { }

5. Add, delete, modify, check

name_set = {'Xiao Wang', 'Da Wang'}
- Add:
name_set.add("Kevin") //Add a single
name_set.update(["Xiao Guang","Da Guang"],["WG"]) / /Added is the sequence
print(name_set)
- delete:
name_set.remove("WG") //Remove non-existing elements and report an error
name_set.discard("WG") //Remove non-existing elements without error
print(name_set)
– Change:
for n_s in name_set:
if n_s == "Xiao Wang":
name_set.remove(n_s)
name_set.add("Kevin")
print(name_set)

6. Intersection and Union

name_set1 = {'Zhang San','Li Si','Wang Wu'}
name_set2 = {'Sun Qi','Li Si'}
– Intersection:
name_set=name_set1 & name_set2
name_set=name_set1.intersection(name_set2)
– Union :
name_set=name_set1 | name_set2
- difference:
name_set=name_set1 - name_set2 //remove intersection from name_set1
name_set=name_set2 - name_set1 //remove intersection from name_set2
- symmetric difference: //union - intersection
name_set=name_set1 ^ name_set2

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325955285&siteId=291194637