Part of using a list in Python - Reference Python programming from entry to practice

 Part of the processing elements in the list - sliced

1. Slice

= Players [ 'Charles', 'Martina', 'Michael', 'Florence', 'Eli'] 
print (Players [0:. 3]) # print slice list, which contains the first three elements, the output is a list of
print (players [1: 4]) # 2,3,4 extracted list element
print (players [: 4]) # index is not specified, it is printed out listing the first four elements of the
print (players [2:]) termination index # is not specified, it prints out a list of all the elements after the second element (not the second one, because the index starts from 0)
Print (Players [-3:]) # index list from right to left at -1, it prints out the last three elements of the list
print (players [: - 2] ) # does not include the designated second index slice, so the printing elements other than the last two elements of
the results:
[ ' Charles', 'Martina', 'Michael']
[ 'Martina', 'Michael', 'Florence']
[ 'Charles',' Martina ',' Michael ',' Florence ']
[' Michael ',' Florence ', 'Eli']
[ 'Michael', 'Florence', 'eli']
['charles', 'martina', 'michael']

2. traverse sections

for player in players [: 3] : # 3 before traversing elements 
print (player.title ())
operating results:
Charles
Martina
Michael

3. Copy List

my_foods = [ 'pizza', ' falafel', 'carrot cake'] # definition list 
friend_foods = my_foods [:] # replication list
Print ( 'My Favorite Foods are:')
Print (my_foods)
Print ( "\ NMY Friend apos Favorite Foods are: ")
Print (friend_foods)
operating results:
My favorite foods are:
['pizza', 'falafel', 'carrot cake']
 
My friend's favorite foods are:
['pizza', 'falafel', 'carrot cake']
Adding an element for each list:
my_foods.append('cannoli')
friend_foods.append('ice cream')
print('My favorite foods are:')
print(my_foods)
print("\nMy friend's favorite foods are:")
print(friend_foods)
运行结果:
My favorite foods are:
['pizza', 'falafel', 'carrot cake', 'cannoli']
 
My friend's favorite foods are:
['pizza', 'falafel', 'carrot cake', 'ice cream']
Copy the code listing if friend_foods = my_foods [:] with friend_foods = my_foods alternative, add code to run on top of how elements of it?
My favorite foods are:
['pizza', 'falafel', 'carrot cake', 'cannoli', 'cannoli', 'ice cream']

 

My friend's favorite foods are:
['pizza', 'falafel', 'carrot cake', 'cannoli', 'cannoli', 'ice cream']
Compare the results found: Code friend_foods = my_foods just two variables point to the same list;
                 Code friend_foods = my_foods [:] is a complete copy of the list to obtain a list of two independent
Note: There will be bracketed Why two different results when copying list.

 

Guess you like

Origin www.cnblogs.com/shirley-yang/p/11031909.html