1.for,while Loop traversal
2. Adding elements
Append
You can add elements to a list by append
#定义变量A,默认有3个元素 A = [‘xiaoWang‘,‘xiaoZhang‘,‘xiaoHua‘] print("-----添加之前,列表A的数据-----") for tempName in A: print(tempName) #提示、并添加元素 temp = input(‘请输入要添加的学生姓名:‘) A.append(temp) print("-----添加之后,列表A的数据-----") for tempName in A: print(tempName)
Results:
Extend
By extend you can add elements from another collection to the list one by one
>>> a = [1, 2]>>> b = [3, 4]>>> a.append(b)>>> a[1, 2, [3, 4]]>>> a.extend(b)>>> a[1, 2, [3, 4], 3, 4]
Insert
Insert (Index, object) inserts an element in the specified position before Index object
>>> a = [0, 1, 2]>>> a.insert(1, 3)>>> a[0, 3, 1, 2]
Del: Delete del xx "0" according to the subscript
Pop: Delete the last element Xx.pop
Remove: Delete Xx.remove (') based on the value of the element
The sort method is to rearrange the list in a specific order, by default, from small to large, and the parameter reverse=true can be changed to reverse, from large to small.
The reverse method is to reverse the list.
Xx.sort ()
Xx.reverse ()
Meta-group
A python tuple is similar to a list, except that the elements of a tuple cannot be modified . tuples use parentheses, and the list uses square brackets.
Dictionary key key value
Note that in the dictionary operation, the dictionary is judged by the key
modifying elements
The data in each element of the dictionary can be modified, as long as it is found by key and can be modified
Demo
info = {‘name‘:‘班长‘, ‘id‘:100, ‘sex‘:‘f‘, ‘address‘:‘地球亚洲中国北京‘} newId = input(‘请输入新的学号‘) info[‘id‘] = int(newId) print(‘修改之后的id为%d:‘%info[‘id‘])
If the "key" in the dictionary does not exist when using the variable name [' key '] = Data , then this element will be added
Delete Element
To delete a dictionary, there are a few things:
- Del Delete
- Clear () Clear
<1>len ()
Number of key-value pairs in the measurement dictionary
<2>keys
Returns a list containing all keys for the dictionary
<3>values
Returns a list containing all the value of the dictionary
<4>items
Returns a list containing all (key, value) Ganso
<5>has_key
Dict.has_key (Key) returns True if key is in the dictionary, otherwise false
Dictionary traversal
For key in XXXX
For value in XXXX
For item in XXXX element
For Key,value in XXXX key value pair
Enumerate () use
- If you want to traverse the index and iterate through the elements on a list, you can first write this:
list1 = ["这", "是", "一个", "测试"]for i in range (len(list1)): print i ,list1[i]
- The above method is somewhat cumbersome, and the use of enumerate () will be more direct and graceful:
list1 = ["这", "是", "一个", "测试"]for index, item in enumerate(list1): print index, item>>>0 这1 是2 一个3 测试
- Enumerate can also receive a second parameter that specifies the index starting value, such as:
list1 = ["这", "是", "一个", "测试"]for index, item in enumerate(list1, 1): print index, item>>>1 这2 是3 一个4 测试
CMP (ITEM1, ITEM2) compares two values
1 0-1
Python notes 03 List Dictionary