Python basics review

Posted by meckr on Thu, 13 Jan 2022 14:39:15 +0100

Article catalog

Content introduction

This section mainly talks about lists in Python basics, and explains the establishment of lists and some basic operations on lists.

1, What is the list?

Python's main built-in types include numbers, sequences, mappings, classes, instances, and exceptions. Sequence is the most basic data structure. Each element in the sequence is assigned a number to represent its position, which is called an index. Generally speaking, the index of the first bit is 0, the index of the second bit is 1, and so on.

Python contains 6 built-in sequences, namely lists, tuples, strings, Unicode strings, buffer objects, and xrange objects. Among them, lists, tuples and strings are the most commonly used sequences.

List is the most commonly used Python data type and can appear as a comma separated value within square brackets.

A list week is created as follows. The basic unit of a list is the elements, separated by commas. The data items of the list do not need to have the same type.

week = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']

     

2, List operation

(1) Index of the list

Lists are ordered collections, so to access any element of a list, you just tell Python the location or index of that element. To access a list element, indicate the name of the list, then the index of the element, and place it in square brackets.

# Lists are ordered collections, so to access any element of a list, you just tell Python the location or index of that element.
# To access a list element, indicate the name of the list, then the index of the element, and place it in square brackets.
week = ['tuesday', 'Wednesday', 'thursday', 'Friday', 'saturday']
print(week)
print(week[3])
print(week[3].title())
# In Python, the index of the first list element is 0 instead of 1. (in Matlab, the first index is 1. The latter is convenient for calculation and practical. Be careful not to confuse it)
# Python provides a flashback reading method, as shown below. When the index is "- 2", it refers to taking the second list element backwards.
print(week[-2])
# Elements in the list can be used like other variables. For example, you can splice printouts with elements in a list.
message = 'Today is '+week[2].title()+' ,tomorrow is '+week[3].title()+ '.'
print(message)

(2) Addition and deletion of list elements

As shown in the following code and figure, note that the differences between "method", "function" and "statement" can be seen here.

# 1. Add an element at the end of the list, which can be used append() method
# Usage is "list name. append('element name ')"
week.append('Sunday')  # Insert sunday at the end of the list
print('\n Add at the end of the list:')
print(week)
# 2. Insert an element anywhere in the list and use The insert() method adds a new element anywhere in the list. To do this, you need to specify the index and value of the new element.
# The usage is "list name. Insert (index (number), 'element name')"
week.insert(0, 'Monday')  # Insert monday at the beginning of the list
print('\n Insert in the middle of the list:')
print(week)
# 3. To delete an element at any position in the list, you can use the del statement. When using, you should know the index of the element to be deleted.
# The usage is "del list name [index of element to be deleted]"
del week[3]
print('\n Delete in the middle of the list:')
print(week)
# 4. Sometimes you need to pop up an element in the list and save it. You can use the pop() method.
# The usage is "a = list name. Pop (element index to pop up)". This statement can pop up the element at the corresponding index in the list and assign it to a, and delete the element in the list at the same time.
TanChuYuanSu = week.pop(-1)  # Pop up the last element -- in particular, if you don't give any parameters in the brackets of pop(), the last element pops up by default.
print('\n Delete from the list and pop up:')
print(week)
print('The pop-up element is:', TanChuYuanSu)
# 5. If you don't know the index and only know the element value, you can use the remove() method to delete an element in the list
print('\n Only know the value but not the deletion of the index:')
BuShangXue = 'saturday'
print('Because I don't go to school, I get rid of it', BuShangXue)
week.remove(BuShangXue)
print(week)
# The remove() method can only delete the first specified value at a time. If the value to be deleted may appear multiple times in the list, you need to use a loop to determine whether all such values have been deleted.

(3) Sort the list and find the length of the list

week = ['Monday', 'tuesday', 'Wednesday', 'thursday', 'Friday', 'saturday', 'Sunday']
week1 = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
number = [1, 23, 4, 5, 1214, 75, 43, 9, 2, 0]
# 1. To permanently sort the list, you can use the sort() method
print('Original list:')
print(week)
print(week1, '\n')
week.sort()
print('List after order:')
print(week)
# It doesn't seem to be sorted alphabetically. Try week1 again
week1.sort()
print(week1, '\n')
# Here, when all elements are capitalized, the sort method successfully arranges them alphabetically from small to large
number.sort()
print(number)
# You can also arrange numbers in this way
number.sort(reverse=True)
print(number, '\n')
# If you give sort a parameter "reverse=True", you can reverse sort from large to small.
# It is worth noting that the sort arrangement is permanent and irreversible. As for why you can't arrange the upper and lower case letters correctly, you need to master the knowledge of ASCII code.
# 2. To preserve the original arrangement order of list elements and present them in a specific order, use the function sorted().
# The function sorted() allows you to display list elements in a specific order without affecting their original order in the list.
week1 = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
print("Original list:")
print(week1)
print("\n use sorted()After sorting by method:")
print(sorted(week1))
print("\n See if the original list has been changed:")
print(week1)
# If you need to arrange the letters in reverse order, you can pass the parameter reverse=True to the function sorted().
print("\n Reverse order:")
print(sorted(week1, reverse=True))
# 3. If you need to arrange the elements in the list in reverse order, you can use the reverse() method. Note that the reverse order here refers to putting the first element in the list to the last, and so on.
week1 = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
print(week1, '\n')
week1.reverse()
print('After reverse order:')
print(week1)
# 4. If you want to know the length of the list, you can use the function len().
print('list week1 The length of the is:', len(week1))

summary

This time, I learned the list of the most common data types in Python. The previous article gave some specific operations on the list and the impact of these operations. Here, a more comprehensive summary is given with reference to the network and books to facilitate subsequent search and use. In view of my limited ability, I welcome criticism and correction.

For list operations:

1.Python Contains the following functions
cmp(list1, list2)
# Compare elements of two lists
len(list)
# Number of list elements
max(list)
# Returns the maximum value of a list element
min(list)
# Returns the minimum value of a list element
list(seq)
# Convert tuples to lists

2.Python Include the following methods:
list.append(obj)
# Add a new object at the end of the list
list.count(obj)
# Counts the number of times an element appears in the list
list.extend(seq)
# Append multiple values in another sequence at the end of the list at one time (expand the original list with the new list)
list.index(obj)
# Find the index position of the first match of a value from the list
list.insert(index, obj)
# Insert object into list
list.pop([index=-1])
# Removes an element from the list (the default last element) and returns the value of that element
list.remove(obj)
# Removes the first occurrence of a value in the list
list.reverse()
# Elements in reverse list
list.sort(cmp=None, key=None, reverse=False)
# Sort the original list

3.Combination and interception:
[a, b, c] + [d, e, f]->[a, b, c, d, e, f]
# Combine two lists
['666'] * 6	->['666', '666', '666', '666', '666', '666']
# Repeat the elements in the list
3 in [1, 2, 3]->True
# Determines whether an element exists in the list and returns a Boolean value
for x in [1, 2, 3]:
# Let x take values in sequence in the list, and the number of cycles is the length of the list
 List name[Header subscript i:Tail subscript j:step k]
list[1:2:66]
# A part of the interception list starts from the element where the first number index is located to the element where the second number index is located, and the step is the third number
# These three numbers can be defaulted. Generally, there are several possibilities:
# 1. Only the header subscript i and colon (representing the interception from the element of the header subscript i to the end)
# eg:list[1:] means to intercept from the second bit, and all contents in and after the second bit are intercepted.
# 2. Only colon and tail subscript j (representing elements intercepted from the beginning to j-1)
# eg:list[:10] indicates that all contents from bit 1 to bit 9 are intercepted.
# 3. There are header subscript i, colon and tail subscript j (representing the elements intercepted from I to j-1)
# eg:list[1:10] indicates that all contents from bit 2 to bit 9 are intercepted.
# 4. There are header subscript i, colon, tail subscript j, colon and step size k (it means starting from I, taking every k steps and intercepting to bit j-1)
# eg:list[1:10:2] means to take every two bits from the second bit to the ninth bit. That is, take out bits 2, 4, 6 and 8.

Topics: Python list