“This article has participated in the good article call order activity, click to see: back end, big front end double track submission, 20,000 yuan prize pool for you to challenge!”

Introduction – In Python, data structures are used to hold important data information in a project. Python has built-in data structures such as lists, tuples, dictionaries, and collections. In this lesson, we’re going to look at one of the most important data structures in Python — lists (also known as sequences). Lists are one of the most basic data structures in Python and can be compared to arrays in other programming languages (C/C++/Java).

Basic concept: Use brackets “[]” to represent lists in Python programs, and use commas to separate the elements.

books = ['Python from starting to Quitting'.'C from entry to abandonment '.'Assembly from Starting to quitting']     Create a list named books
            
print(books)                                                      Output the information in the list books
Copy the code

In the above code, create a list named “books”, store three elements in the list, and then print out the list.

Index and Slice in the list in Section 1

Note: Indexes and slices work for any data type.Copy the code

① I want to teach you how to take the elements in the list. (Smart students have already answered the index value!)

In A Python program, because a list is an ordered collection, all you need to do to access any element in the list is to tell Python its position or index (but note: the index of the elements in the list starts at 0!). . To access a list element, indicate the name of the list, then indicate the index of the list, and place it in square brackets.

The SAO operation strikes: What if we don’t know how long the list of items is in a project, and we just want the last element? In fact, there are many ways to oh! But the teacher here tells us a SAO operation to take it by subscript:

a = [1.2.3.4.5.6.7.8.9.10]
print(a[-1])				# output 10. If you go from the right to the left of the list the first one is minus 1, and so on.
Copy the code

② Good good students seriously, WE want to talk about the key – first of all, the teacher will list slices of the universal formula to everyone (a universal formula is not feeling cow force, but the students do not form a inertia of thinking, see the universal formula on the back of the thing oh! To understand it thoroughly through the teacher’s explanation below!

Slice (universal formula one note: left closed right open!) First: positive direction [start position: end position +1: step size] Second: note (if the step size is negative, reverse order) reverse direction [start position: end position -1: negative]Copy the code

Is not to see the universal formula after a head meng, that is right, all give me up, let’s have a good study of the universal formula is what meaning!

(1) The first universal formula (two actual code snippets to teach you) — positive direction [start position: end position +1: step size]

Knowledge depot (an easy way to create a list of numbers - use the method range(), note that this method also closes left and opens right!) Numbers = list(range())0.11))
print(numbers)		[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Copy the code

The first code snippet explains:

Positive means it’s going from left to right!

The starting position is the starting index of the list element you want to retrieve;

The end position is the end index of the list element you want to get plus one.

The step is a number of indexes to jump each time. The default value is 1.

numbers = list(range(0.11))

print(numbers[0:5])			Print (numbers[0:5:1])
Copy the code

The second code snippet explains:

Given a list a = [1,2,3,4,5,6,7,8,9,10], we need to take all the odd numbers in the list — that’s where forward slicing comes in!

a = [1.2.3.4.5.6.7.8.9.10]

print(a[0: (9+1) :2])				# print(a[0(start):9+1(end):2))
Copy the code

Perfect completion of demand!

Small problems in class (will raise your hand quickly quickly – plus usual grades oh!

How do I take all the even numbers in this list?

Answer: print (a [1(Starting position):9+1(End position +1) :2(take every two times)])2.4.6.8.10]
Copy the code

(2) The second universal formula (two actual code snippets to teach you) – opposite [start position: end position: -1: negative]

Note: If the step size is negative, reverse the order!

The first code snippet explains:

Positive means it’s going from left to right!

The starting position is the end index of the list element (including this one!) that you want to retrieve. ;

The end position is the starting index of the list element you want to retrieve minus one.

The step size is how many indexes to jump per value. If the slice is in reverse order, you must give the negative step size! .

a = [1.2.3.4.5.6.7.8.9.10]

print(a[9:1: -1])
Copy the code

The second code snippet explains:

Given a list a = [1,2,3,4,5,6,7,8,9,10], we need to take all the even numbers in the list in reverse order — that’s inverted slice!

a = [1.2.3.4.5.6.7.8.9.10]

print(a[::-2])			If you do not write the start and end positions, the whole list will be used
Copy the code

Perfect realization of requirements:

The second section of the lesson list of SAO method operations

① x.apppend () adds a single value!! The list of exclusive

a = [1.2.3]
a.append('s')

print(a)		# output: [1, 2, 3, 's']
Copy the code

* * (2) insert (x, y) – > add custom location element, the element is inserted into the specified index to join a single value!!!!!! (Parameter meaning: The first is the location specified by the subscript to be added, and the second is the element to be added.) **

a = [1.2.3]
a.insert(1.'new_num')		# 
print(a)		# output: [1, 'new_num', 2, 3]
Copy the code

③ extend() — > Inserts at the end of the list, insertable sequence types (strings, lists, tuples), splitting each element. Add multiple values!!

a = [1.2.3]
a.extend('abc')
print(a)		[1, 2, 3, 'a', 'b', 'c']
Copy the code

**④pop() — > delete the last element in the list if no argument is passed, or delete the element at the specified index position **

# No arguments -- remove last element!
a = [1.2.3]
a.pop()
print(a)		# output [1,2]Add argument -- delete the element at the specified index position! b = [1.2.3]
a.pop[1]
print(a)        # output [1,3]
Copy the code

⑤remove() — > remove the specified element, but only remove the first item if there are multiple identical items

a = [1.2.3.4.1.1.1]
a.remove(1)
print(a)		# output: [2,3,4,1,1,1]
Copy the code

**⑥clear() — > remove all values from the list

a = [1.2.3.4.1.1.1]
a.clear()
print(a)		# output as []
Copy the code

⑦ Count () — > count()

a = [1.2.3.4.1.1.1]
num = a.count(1)
print(num)			# output 4
Copy the code

Index (x,y) — > index(x,y) — > index(x,y) — > index(x,y) — > index(x,y) — > index(x,y) — > Each lookup displays only the index of the first value found. If you do not add a second argument, start at index 0 by default. If you do not find a value, you will report an error.

a = [1.2.3.4.1.1.1]

index1 = a.index(1)
index2 = a.index(1.2)

print(index1)		# output 0
print(index2)		# output 4
Copy the code

⑨ Join () — > method is used to join the elements in the sequence with the specified character to produce a new string. Use str.join(sequence), where sequence indicates the sequence of elements to be joined. Returns a new string generated by concatenating elements in a sequence with the specified character.

a = ['a'.'b'.'c']

end = "-".join(a)
print(end)		# output a-b-c
Copy the code

⑩ List operations also include deep and shallow replication. See this article for more detailsOne lesson will teach you how to thoroughly understand one of the most frequently asked interview questions in Python. (All the merit students have taken out their notebooks to take notes in class.)

Extension: list sorting method!

1.sort() --> sort the list from small to large, only numbers, if there are strings in the list then add: key= STR (a.ort (key= STR)). String sorting is based on ASCII alphabetic sorting. Above code: a = ['a'.'d'.'f'.'b']
a.sort(key=str)
print(a)		['a', 'b', 'd', 'f']Extension: usesortThe () method sorts the values in the list from largest to smallest; Add key= STR if there is a string in the list, such as a.ort (key= STR,reverse=True). Above code :(list contains strings) a = ['a'.'g'.'b'.'c']
a.sort(key=str,reverse=True)
print(a)		['g', 'c', 'b', 'a'](list elements are all numbers) a = [1.9.3.7]
a.sort(reverse=True)
print(a)		# output: [9,7,3,1]②reverse() --> Reverse () --> Reverse () --> reverse() Above code: a = [1.4.3.8]
a.reverse()
print(a)		# output: [8,3,4,1]
Copy the code

For those of you who want to write the list optional question for our final exam, listen up — here are some lists you can use on projects!

(1) Find the most frequent element in the list

If one day the class is at work and the Boss suddenly throws out a request: ** How to find the most frequently occurring elements in the list in the Python program! ** Are you going to mess around with loops or something? It’s inefficient and B is not very efficient. Here is an easy way to get started: use the Counter class in the Collections module and call the most_common() function in the Counter class. Go directly to the code:

from collections import Counter
words = [
    'look'.'into'.'my'.'AAA'.'look'.'into'.'my'.'AAA'.'the'.'AAA'.'the'.'eyes'.'not'.'BBB'.'the'.'AAA'."don't".'BBB'.'around'.'the'.'AAA'.'look'.'into'.'BBB'.'AAA'.'BBB'.'under'
]

word_counts = Counter(words)
print(Count the number of occurrences of all elements:,word_counts)
top_three = word_counts.most_common(3)
print('Count the three most frequently occurring elements:',top_three)
Copy the code
Output: Count the number of occurrences of all elements: Counter({'AAA': 6.'the': 4.'BBB': 4.'look': 3.'into': 3.'my': 2.'eyes': 1.'not': 1."don't": 1.'around': 1.'under': 1}) count the three most frequently occurring elements: [('AAA'.6), ('the'.4), ('BBB'.4)]
Copy the code

(2) Sort the instance defined by the class

Project Background: What if we have multiple instances of a class definition in a project and our requirement is to order the instances?

The built-in function sorted() accepts an argument key that passes a callable object. The callable returns some of the values in the object to be sorted, and the sorted() function uses those values to compare objects.

If you have multiple instances of a User object in your program, and you want to sort them by the attribute user_id, you can provide a callable object that takes the User instance as input and returns the user_ID. The following code demonstrates sorting the above User object instances:

class User:
    def __init__(self, user_id) :
        self.user_id = user_id

    def __repr__(self) :
        return 'User({})'.format(self.user_id)

# Original sort
users = [User(91), User(17), User(18)]
print(users)

# Sort by user_id -- both methods
# ① Use a lambda expression:
print(sorted(users, key=lambda u: u.user_id))

# ② Use the built-in operator.attrgetter() function to handle this:
from operator import attrgetter
print(sorted(users, key=attrgetter('user_id')))
Copy the code

(3) Named slices (advanced usage)

Background: In Python programs, you sometimes find yourself writing code that overuses hard-coded slice indexes (as in section 2 above!). , and our project code becomes cluttered and unreadable, and we need to clean it up. Also, excessive use of hard-coded index values reduces the readability and maintainability of the code.

Solution: In Python programs, you can use the function slice() to implement slicing objects, to implement parameter passing in the slicing function, and to use it anywhere slicing is allowed.

Use the syntax format of the function slice() :class slice(stop)
class slice(start.stop.step)

start: starting position;stop: End position;step: spacing.Copy the code

The above code is explained:

items = [0.1.2.3.4.5.6]

a = slice(2.4)          # Define a slice object instance a

print(items[2:4])       Use the usual slice to get the list value
print(items[a])         Use slice object instance a to get list values

items[a] = [10.11]
print(items)

print(a.start)          Use the attributes a.tart, a.top, and a.tep to obtain information about the slice object
print(a.stop)
print(a.step)

s = 'verygoodman'
Use the indices(size) function to map slices to a sequence of a specific size. This will return a tuple of (start,stop,step),
# All values have been restricted to exactly within the bounds, so that IndexError is avoided when indexing.
print(a.indices(len(s)))   
print(*a.indices(len(s)))		# Decompose tuples
for i in range(*a.indices(len(s))):
    print(s[i])
Copy the code

In depth – the benefits of using the indices(size) function, and how you can avoid an IndexError exception when indexing, as described in the comments above! Go straight to the code:

a = slice(2.4)          # Define a slice object instance a

s = 'ver'				# This sequence s
Use the indices(size) function to map slices to a sequence of a specific size. This will return a tuple of (start,stop,step),
# All values have been restricted to exactly within the bounds, so that IndexError is avoided when indexing.
print(a.indices(len(s)))
print(*a.indices(len(s)))		# Decompose tuples
for i in range(*a.indices(len(s))):
    print(s[i])
Copy the code

One lesson to thoroughly understand the difference between a single asterisk (*) and a double asterisk (**) in Python and how to use it in real projects — teach me!

The indices(size) function limits the slice scope to within the sequence scope boundary of the mapped sequence. The indices(size) function limits the slice scope to within the sequence scope boundary of the mapped sequence. The indices(size) function limits the slice scope to within the sequence scope boundary of the mapped sequence. In this case, we define a slice object instance outside the scope of the sequence s, but the use of the indices(size) function does not report an error, and is similar to a dynamic adaptive change!

(4) List generators (advanced usage)

List Comprehensions are an elegant way to simplify your code. Official documentation – ** List derivation provides a neat way to create lists. ** Using list comprehensions makes it very simple to construct a new list, using only a simple expression to transform the resulting elements.

Use the syntax format of the Python list derivation: variable = [out_exp_res for out_exp in input_list if out_exp= =2] out_exp_res: List generated element expression, can be a function with a return value;for out_exp inInput_list: Iterate over input_list, passing out_exp into the out_exp_res expression;if out_exp == 2: Determines which values can be filtered based on conditions.Copy the code

Number one: basic use

Problem 1: Create a list of squares from 1 to 10.

Conventional thinking — conventional solutions:

list_end = []
for x in range(10):
    list_end.append(x**2)
print(list_end)
Copy the code

With a list derivation — one line of code:

list_end1 = [x**2 for x in range(10)]
print(list_end1)
Copy the code

Both outputs are:

The second problem: output an integer that can be divided by 3 within 30.

Traditional methods:

nums = []
for x in range(30) :if x % 3= =0:
        nums.append(x)
print(nums)
Copy the code

One line of code using list derivation:

nums1 = [x for x in range(30) if x % 3= =0]
print(nums1)
Copy the code

Both outputs are:

Second: Upgrade use — Use the list generator and use the function processing

Requirement: First get the integer that can be divided by 3 within 30, and then output the square of the obtained integer once.

def squared(x) :
    return x**2

end = [squared(x) for x in range(30) if x % 3= =0]
print(end)
Copy the code

Third: The advanced version uses — the advanced operation of deleting specific elements from the list

In Python programs, there are times when filtering specific elements in a list that the filter criteria cannot simply be represented in a list derivation or generator expression, such as when the filtering process involves exception handling or other complex details. Consider putting the code that handles filtering into a separate function and using the built-in filter() function for processing.

Requirement: Filter all integer elements in the specified list!

values = ['1'.'2'.'- 3'.The '-'.'4'.'N/A'.'5']
def is_int(val) :
    try:
        x = int(val)
        return True
    except ValueError:
        return False

# Note: Since we created an iterator with filter(), we must add the list() function before filter() to get a list result.
isvals = list(filter(is_int, values))
print(isvals)
Copy the code

(5) Remove duplicate elements from the list and keep the order unchanged

The first version:

Requirement: Remove recurring elements from the list and keep the order in which the remaining elements are displayed. If the elements stored in the sequence areHashable, this feature can be implemented using collections and generators.

If an object is hashed, it must be immutable for its lifetime, which requires a __hash__() method. In Python programs, integers, floating point numbers, strings, and tuples are immutable.Copy the code

The code:

def fun(items) :
    seen = set(a)for item in items:
        if item not in seen:
            yield item
            seen.add(item)

if __name__ == '__main__':
    a = [5.3.3.8.6.5.9]
    print(a)
    print(list(fun(a)))
Copy the code

Second edition:

The code above has a flaw — it only works if the elements in the sequence are hashed. How do you do this in a sequence of objects that cannot be hashed? The code:

def fun(items, key=None) :
    seen = set(a)for item in items:
        val = item if key is None else key(item)
        if val not in seen:
            yield item
            seen.add(val)

if __name__ == '__main__':
    a = [
        {'x' :2.'y':3},
        {'x' :1.'y':4},
        {'x' :2.'y':3},
        {'x' :2.'y':3},
        {'x' :10.'y':15}]print(a)
    print(list(fun(a, key=lambda a: (a['x'], a['y'))))Copy the code

Note: The key argument in function fun() in the above code converts the elements in the sequence to hashing types in order to detect duplicate options.

Original author - Lonely. If you need to reprint, please contact me first, by my permission to be reprinted; Unauthorized reprint ****.Copy the code

About the author: Loner, devoted to python crawler and Web (love Django, Flask, Tornado) for 30 years! Welcome to follow the same name CSDN blogger name [Lonely], as well as the newly created wechat public account [Lonely], adhere to the output of dry goods, if learning questions welcome to exchange!