Article directory
Format of <1> List
Sequences are the most basic data structure in Python.
- Format
#The type of variable A is a list. namesList = ['xiaoWang','xiaoZhang','xiaoHua'] print(namesList[0]) print(namesList[1]) print(namesList[2]) # What's more powerful than C's arrays is that the elements in the list can be of different types. testList = [1, 'a']
- visit
#!/usr/bin/python list1 = ['physics', 'chemistry', 1997, 2000] list2 = [1, 2, 3, 4, 5, 6, 7 ] print "list1[0]: ", list1[0] print "list2[1:5]: ", list2[1:5]
The output of the above example is as follows:
list1[0]: physics
list2[1:5]: [2, 3, 4, 5]
< 2 > Printed List
- Use the for loop
namesList = ['xiaoWang','xiaoZhang','xiaoHua'] for name in namesList: print(name)
- Use the while loop
namesList = ['xiaoWang','xiaoZhang','xiaoHua'] length = len(namesList) i = 0 while i<length: print(namesList[i]) i+=1
List script operator < 3 >
The list pair + and * operators are similar to strings. + Number * is used for combination lists and * is used for repetition lists.
Python expression | Result | describe |
---|---|---|
len([1, 2, 3]) | 3 | length |
[1, 2, 3] + [4, 5, 6] | [1, 2, 3, 4, 5, 6] | combination |
['Hi!'] * 4 | ['Hi!', 'Hi!', 'Hi!', 'Hi!'] | repeat |
3 in [1, 2, 3] | True | Does the element exist in the list? |
for x in [1, 2, 3]: print x, | 1 2 3 | iteration |
>>>L = ['Google', 'Runoob', 'Taobao'] >>> L[2] 'Taobao' >>> L[-2] 'Runoob' >>> L[1:] ['Runoob', 'Taobao'] >>>
Description:
Python expression | Result | describe |
---|---|---|
L[2] | 'Taobao' | Read the third element in the list |
L[-2] | 'Runoob' | Read the penultimate element in the list |
L[1:] | ['Runoob', 'Taobao'] | Starting with the second element, intercept the list |
Related operations of < 4 > List
Python contains the following functions:
Ordinal number function |
---|
1. cmp(list1, list2) |
Compare the elements of two lists |
2. len(list) |
Number of list elements |
3. max(list) |
Returns the maximum of list elements |
4. min(list) |
Returns the minimum of list elements |
5. list(seq) |
Converting tuples to lists |
Python includes the following methods:
Serial number method |
---|
1. list.append(obj) |
Add new objects at the end of the list |
2. list.count(obj) |
Statistics of the number of times an element appears in a list |
3. list.extend(seq) |
Append multiple values in another sequence at the end of the list at once (expand the original list with a new list) |
4. list.index(obj) |
Find the index location of the first match of a value from the list |
5. list.insert(index, obj) |
Insert objects into the list |
6. list.pop([index=-1]) |
Remove an element from the list (default last element) and return the value of that element |
7. list.remove(obj) |
Remove the first match of a value in the list |
8.list.reverse() |
Elements in the reverse list |
9. list.sort(cmp=None, key=None, reverse=False) |
Sort the original list |
- Add elements ("add" append, extend, insert)
- append
append lets you add elements to a list
#Define variable A with three elements by default A = ['xiaoYu','xiaoHu','xiaoGuo'] print("----------") for tempName in A: print(tempName) #Prompt and add elements temp = input('name:') A.append(temp) print("-----after add-----") for tempName in A: print(tempName)
xiaoYu
xiaoHu
xiaoGuo
name:111
-----after add-----
xiaoYu
xiaoHu
xiaoGuo
111
- extend
You can add elements from another collection to the list one by one through extension
a = [1, 2] b = [3, 4] a.append(b) print a a.extend(b) print a
[1, 2, [3, 4]]
[1, 2, [3, 4], 3, 4]
- insert
insert(index, object) inserts the element object before the specified position index
a = [0, 1, 2] a.insert(1, 3) print a
[0, 3, 1, 2]
- Modify elements ("change")
#Define variable A with three elements by default A = ['xiao1','xiao2','xiao3'] print("----------") for tempName in A: print(tempName) #Modifying elements A[1] = 'xiao4' print("-----after modify-----") for tempName in A: print(tempName)
xiao1
xiao2
xiao3
-----after modify-----
xiao1
xiao4
xiao3
- Find Elements ("Find" in, not in, index, count)
The so-called lookup is to see if the specified element exists.
in, not in
The common methods of searching in python are:
- in (exists), if it exists, then the result is true, otherwise it is false.
- not in, if not, then the result is true, otherwise false
#List to be found nameList = ['xiao1','xiao2','xiao3'] #Get the name the user is looking for findName = input('name:') #Find out if it exists if findName in nameList: print('same name') else: print('not same')
name:222
not same
Explain:
If the in method is used, then not in is the same, but not in judges that it does not exist.
- index, count
index and count are used in the same way as in strings
a = ['a', 'b', 'c', 'a', 'b']
a.index('a', 1, 3) # Note that the left closed right open interval
Traceback (most recent call last):
File "", line 1, in
ValueError: 'a' is not in list
a.index('a', 1, 4)
3
a.count('b')
2
a.count('d')
0
- Delete elements ("Delete", del, pop, remove)
Analogy in real life, if a classmate transferred, then the name of the student after this article should be deleted; in the development of this function is often used to delete.
The common deletion methods of list elements are:
del: Delete by subscript
pop: Delete the last element
remove: Delete based on the value of the element
demo:(del)
movieName = ['Pirates of the Caribbean','Hacker empire','First Blood','Lord of the rings','The Hobbit','Fast & Furious'] print('------Before deleting------') for tempName in movieName: print(tempName) del movieName[2] print('------After deletion------') for tempName in movieName: print(tempName)
Result:
Before deletion Pirates of the Caribbean Hacker empire First Blood Lord of the rings The Hobbit Fast & Furious After deletion - ---------------------------------------------------------------------------------------------------------- Pirates of the Caribbean Hacker empire Lord of the rings The Hobbit Fast & Furious
demo:(pop)
movieName = ['Pirates of the Caribbean','Hacker empire','First Blood','Lord of the rings','The Hobbit','Fast & Furious'] print('------Before deleting------') for tempName in movieName: print(tempName) movieName.pop() print('------After deletion------') for tempName in movieName: print(tempName)
Result:
Before deletion
Pirates of the Caribbean
Hacker empire
First Blood
Lord of the rings
The Hobbit
Fast & Furious
After deletion - ----------------------------------------------------------------------------------------------------------
Pirates of the Caribbean
Hacker empire
First Blood
Lord of the rings
The Hobbit
demo:(remove)
movieName = ['Pirates of the Caribbean','Hacker empire','First Blood','Lord of the rings','The Hobbit','Fast & Furious'] print('------Before deleting------') for tempName in movieName: print(tempName) movieName.remove('Lord of the rings') print('------After deletion------') for tempName in movieName: print(tempName)
Result:
Before deletion
Pirates of the Caribbean
Hacker empire
First Blood
Lord of the rings
The Hobbit
Fast & Furious
After deletion - ----------------------------------------------------------------------------------------------------------
Pirates of the Caribbean
Hacker empire
First Blood
The Hobbit
Fast & Furious
- sort (reverse)
The sort method is to rearrange the list in a specific order. By default, the list is from small to large, and the parameter reverse=True can be changed to reverse order, from large to small.
The reverse method is to invert the list.
a = [1, 2, 3, 4] print a a.reverse() print a a.sort() print a a.sort(reverse=True) print a
[1, 2, 3, 4]
[4, 3, 2, 1]
[1, 2, 3, 4]
[4, 3, 2, 1]
Nesting of < 5 > lists
Nesting
Similar to nesting of while loops, lists also support nesting
An element in a list is another list, so this is nesting of lists.
schoolNames = [['Peking University','Tsinghua University'], ['Nankai University','Tianjin University','Tianjin Normal University'], ['Shandong University','Ocean University of China']]
- Application
There are three offices in a school. Now there are eight teachers waiting for the allocation of jobs. Please write a program to complete the random allocation.
#encoding=utf-8 import random # Define a list to hold three offices offices = [[],[],[]] # Define a list to store the names of eight teachers names = ['A','B','C','D','E','F','G','H'] i = 0 for name in names: index = random.randint(0,2) offices[index].append(name) i = 1 for tempNames in offices: print('Office%d The number of people is:%d'%(i,len(tempNames))) i+=1 for name in tempNames: print("%s"%name,end='') print("\n") print("-"*20)