Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to master the Python list

2025-02-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "how to master Python list", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let Xiaobian take you to learn "how to master Python list"!

1. basic syntax

The most basic list understanding is the following syntax.

As mentioned earlier, it can be handy for doing certain things, such as creating lists. The extended form is usually represented as a for loop, where each item of iterable runs some operation specified in the expression.

# list comprehension [expression for item in iterable]# expanded form for item in iterable: expression

2. create a list

Undoubtedly, the most popular usage is to simply create a list.

Assuming you don't know what a list is, you might do something like this when creating a list. First declare an empty list. Then in the for loop, append each item to the list.

>>> pets = ( bird , snake , dog , turtle , cat , hamster ) >>> uppercased_pets = [] >>>for pet in pets: ... uppercased_pets.append(pet.upper()) ... >>> uppercased_pets [ BIRD , SNAKE , DOG , TURTLE , CAT , HAMSTER ]

As mentioned in the Basic Syntax section, for loop statements can be "compressed" into a single line--that is, understood as lists containing only one line of code, and we can easily create a list by iterating over the original list.

>>> pets = ( bird , snake , dog , turtle , cat , hamster ) >>> uppercased_pets = [pet.upper() for pet in pets] >>> uppercased_pets [ BIRD , SNAKE , DOG , TURTLE , CAT , HAMSTER ]

3. filter conditional statement

Sometimes, when you use list understanding to create a list, you don't want to include all the items in an existing list.

In this case, a conditional statement is needed to filter out items in the existing list that do not meet certain criteria. The corresponding list understanding has the following syntax.

# list comprehension with a conditional statement [expression for item in iterable if some_condition] # expanded form for item in iterable: if some_condition: expression

view rawlist.py hosted with ❤ by GitHub

Here is an example of the above usage:

>>> primes = [2, 3, 5,7, 11, 13, 17, 19, 23, 29] >>> squared_primes = [x*x for x in primes if x == 3] >>> squared_primes [9, 169, 529]

If you have more complex conditional evaluations, you can even use functions.

>>>defhas_four_legs(pet): ... return pet in ( pig , dog , turtle , hamster , cat ) ... >>> pets = ( bird , snake , dog , turtle , cat , hamster ) >>> four_legs_pets = [pet.capitalize() for pet in pets ifhas_four_legs(pet)] >>> four_legs_pets [ Dog , Turtle , Cat , Hamster ]

4. conditional assignment

Sometimes you don't want to filter items from the original list. Instead, you want to evaluate conditions to determine which expression to use. The syntax and its usage are given below, and the syntax is explained accordingly.

# basic syntax [expression0 if some_condition else expression1 for item in iterable] # syntax explained: compared to the list comprehension s basic syntax: [expression for item in iterable], we can thin about that (expression0 if some_condition else expression1) is a whole part that constitutes the expression in the general format >>> max_value =10 >>> numbers = (7, 9, 11, 4, 3, 2, 12) >>> ceiling_numbers0 = [number if number >> ceiling_numbers0 [7, 9, 10, 4, 3, 2, 10] >>> ceiling_numbers1 = [(number if number >> ceiling_numbers1 [7, 9, 10, 4, 3, 2, 10]

5. Replace map()

In some cases, you might see people creating lists using map(). Specifically, the map() function has the following syntax and its basic usage examples.

Note that the map() function returns an iterable object, so you can use the list() function to generate a list from this iterable object.

# map() returns an iterator object map(function, iterable) >>> pets = ( bird , snake , dog , turtle , cat , hamster ) >>> uppercased_pets =list(map(str.upper, pets)) >>> uppercased_pets [ BIRD , SNAKE , DOG , TURTLE , CAT , HAMSTER ]

As shown earlier, the map() function can be replaced with list comprehension.

>>> pets = ( bird , snake , dog , turtle , cat , hamster ) >>> uppercased_pets = [pet.upper() for pet in pets] >>> uppercased_pets [ BIRD , SNAKE , DOG , TURTLE , CAT , HAMSTER ]

6. Nested List Understanding

Suppose there is a tuple in the code snippet below and you want to create a new list of entries such that the entries are the squares of all the numbers in the tuple.

In this case, nested list understanding can be used, with the syntax shown below.

# basic syntax of the nested list comprehensions [expression for sublist in outer_list for item in sublist] # expanded form for sublist in outer_list: for item in sublist: expression >>> nested_numbers = ((1, 4, 7, 8), (2, 3, 5)) >>> squares = [x*x for numbers in nested_numbers for x in numbers] >>> squares [1, 16, 49, 64, 4, 9, 25]

view rawnested.list.py hosted with ❤ by GitHub

Although technically nested lists can have multiple levels of understanding, more than two levels are not recommended for readability.

7. Using the Walrus operator

A new feature in Python 3.8 is the introduction of the walrus operator (:=) for assignment expressions.

Assuming ten extractions from the list of letters, the list created will include only the vowels in these diagrams. The following shows how to use the walrus operator in list comprehension.

Specifically, in the following example, it is evaluated whether a random letter extracted from a letter is a vowel, and if so, it is classified into letters accessible to a list understanding expression.

>>> letters =list( this is to produce a list of letters ) >>> letters [ t , h , i , s , , i , s , , t , o , , p , r , o , d , u , c , e , , a , , l , i , s , t , , o , f , , l , e , t , t , e , r , s ] >>>import random >>> vowels = [letter.upper() for _ inrange(0, 10) if (letter := random.choice(letters)) inlist( aeoui )] >>> vowels [ I , O , O , O , O ]

8. collective understanding

Although many people know about list understanding, understanding can also be used when creating collections. The basic syntax and its usage are shown below.

One major difference is that we use curly brackets instead of square brackets. Of course, by design, there is no duplication of elements in a collection, as opposed to lists that allow duplication.

Note that conditional statements can also be used in set understanding.

# syntax for set comprehension {expression for item in iterable} >>> numbers = (1, 34, 5, 8, 10, 12, 3, 90, 70, 70, 90) >>> unique_even_numbers = {number for number in numbers if number%2==0} >>> unique_even_numbers {34, 70, 8, 10, 12, 90}

9. dictionary understanding

Knowing list and set understanding, it's no surprise that Python also has dictionary understanding. The following code snippet shows the basic syntax and its usage.

# syntax for dict comprehension {key_expression : value_expression for item in iterable} >>> words =( python , is , a , big , snake ) >>> len_words = {word : len(word) for word in words} >>> len_words { python : 6, is : 2, a : 1, big : 3, snake : 5} >> len_words_p = {word : len(word) for word in word if word.startswith( p )}>> len_words_p { python : 6} At this point, I believe that everyone has a deeper understanding of "how to master Python lists". Let's actually operate it! Here is the website, more related content can enter the relevant channels for inquiry, pay attention to us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report