current position:Home>Python notes (XV): List derivation
Python notes (XV): List derivation
2022-01-30 15:41:23 【A bowl week】
Little knowledge , Great challenge ! This article is participating in “ A programmer must have a little knowledge ” Creative activities .
Hello everyone , I am a A bowl week , One doesn't want to be drunk ( Internal volume ) The front end of the . If you are lucky enough to get your favor , I'm very lucky ~
List generator
List generation is List Comprehensions, yes Python Built in very simple but powerful can be used to create list Generative form of .
The syntax is as follows :
# Ordinary generative
[ expression for Variable in Old list ]
# Conditional generating formula
[ expression for Variable in Old list if Conditions ]
# if...else Conditional generating formula
[ expression if Conditions 1 else Conditions 2for Variable in Old list ]
Copy code
Case study
- Not enough letters to filter out nouns 4 Name , The sample code is as follows :
names = ["Tom", "Lily", "Jack", "Steven", "Bod"]
# In the process of not using list generation
news_names = []
for name in names:
if len(name) > 3:
news_names.append(name)
print(news_names) # ['Lily', 'Jack', 'Steven']
# Use list generation
new_names = [name for name in names if len(name) > 3]
print(new_names) # ['Lily', 'Jack', 'Steven']
Copy code
Obvious , Using list generation can save a lot of lines of code
- take 1-100 Integers can be 3 and 5 Divisible numbers , Make a new list . Sample code , The sample code is as follows :
# take 1-100 Integers can be 3 and 5 Divisible numbers , Make a new list
# The old way
number_list = []
for i in range(101):
if i % 3 == 0 and i % 5 == 0:
number_list.append(i)
print(number_list) # [0, 15, 30, 45, 60, 75, 90]
# List generator
new_num_list = [i for i in range(101) if i % 3 == 0 and i % 5 == 0]
print(new_num_list) # [0, 15, 30, 45, 60, 75, 90]
Copy code
- take 0 To 10 Odd sum of 0 To 5 Even numbers of form a non repeating list , The sample code is as follows :
# take 0 To 10 Odd sum of 0 To 5 Even numbers of form a non repeating list
# The old way
news_number_list = []
for x in range(10):
if x % 2 != 0:
for y in range(5):
if y % 2 == 0:
news_number_list.append([x, y])
print(news_number_list)
# [[1, 0], [1, 2], [1, 4], [3, 0], [3, 2], [3, 4], [5, 0], [5, 2], [5, 4], [7, 0], [7, 2], [7, 4], [9, 0], [9, 2],[9, 4]]
# The new method
news_num_list = [[x, y]
for x in range(10) if x % 2 != 0 for y in range(6) if y % 2 == 0]
print(news_num_list)
# [[1, 0], [1, 2], [1, 4], [3, 0], [3, 2], [3, 4], [5, 0], [5, 2], [5, 4], [7, 0], [7, 2], [7, 4], [9, 0], [9, 2],[9, 4]]
Copy code
It also supports multiple for sentence , If you use the original method, the hierarchy is too deep , Use generative one line to solve
- Make the number in the list greater than 8000 Plus 200 Less than or equal to 8000 Plus 500, The sample code is as follows :
# Make the number in the list greater than 8000 Plus 200 Less than or equal to 8000 Plus 500
number = [5000, 10000, 4500, 80000, 12000]
# The old way
for i in number:
if i > 8000:
i += 200
else:
i += 500
print(number) # [5000, 10000, 4500, 80000, 12000]
# The new method
new_number = [i + 200 if i > 8000 else i + 500 for i in number]
print(new_number) # [5000, 10000, 4500, 80000, 12000]
Copy code
Set generative
The grammatical structure is as follows :
# Ordinary generative
{ expression for Variable in Old list }
# Conditional generating formula
{ expression for Variable in Old list if Conditions }
# if...else Conditional generating formula
{ expression if Conditions 1 else Conditions 2for Variable in Old list }
Copy code
The syntax structure is basically the same as that of list generation , But because the set does not allow duplicates , All the results are automatically de duplicated
Dictionary generative
The syntax structure of dictionary generation is consistent with that of set generation and list generation , The only difference is that dictionaries store information in the form of key value pairs , In the following example, we will dict Key value exchange in , The sample code is as follows :
# Exchange the key value pairs of the dictionary
dict1 = {"a": "A", "b": "B", "c": "C"}
# Just the way
new_dict1 = {}
for key, value in dict1.items(): # Returns a tuple containing key value pairs
new_dict1[value] = key
print(new_dict1) # {'A': 'a', 'B': 'b', 'C': 'c'}
# The new method
news_dict1 = {value: key for key, value in dict1.items()}
print(news_dict1) # {'A': 'a', 'B': 'b', 'C': 'c'}
Copy code
item
Method : Return traversable ( key , value ) Tuple array .
copyright notice
author[A bowl week],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201301541203537.html
The sidebar is recommended
- Python notes (6): definition and use of lists
- Python notes (V): string operation
- Python notes (IV): use of functions and modules
- Python notes (3): conditional statements and circular statements
- Python notes (II): lexical structure
- Notes on python (I): getting to know Python
- [Python data structure series] - tree and binary tree - basic knowledge - knowledge point explanation + code implementation
- [Python daily homework] Day7: how to combine two dictionaries in an expression?
- How to implement a custom list or dictionary in Python
- 15 advanced Python tips for experienced programmers
guess what you like
-
Python string method tutorial - how to use the find() and replace() functions on Python strings
-
Python computer network basics
-
Python crawler series: crawling global airport information
-
Python crawler series: crawling global port information
-
How to calculate unique values using pandas groupby
-
Application of built-in distribution of Monte Carlo simulation SciPy with Python
-
Gradient lifting method and its implementation in Python
-
Pandas: how to group and calculate by index
-
Can you create an empty pandas data frame and fill it in?
-
Python basic exercises teaching! can't? (practice makes perfect)
Random recommended
- Exploratory data analysis (EDA) in Python using SQL and Seaborn (SNS).
- Turn audio into shareable video with Python and ffmpeg
- Using rbind in python (equivalent to R)
- Pandas: how to create an empty data frame with column names
- Talk about quantifying investment using Python
- Python, image restoration in opencv - CV2 inpaint
- Python notes (14): advanced technologies such as object-oriented programming
- Python notes (13): operations such as object-oriented programming
- Python notes (12): inheritance such as object-oriented programming
- Chapter 2: Fundamentals of python-5 Boolean
- Python notes (11): encapsulation such as object-oriented programming
- Python notes (10): concepts such as object-oriented programming
- Gradient lifting method and its implementation in Python
- Van * Python | simple crawling of a site course
- Chapter 1 preliminary knowledge of pandas (list derivation and conditional assignment, anonymous function and map method, zip object and enumerate method, NP basis)
- Nanny tutorial! Build VIM into an IDE (Python)
- Fourier transform of Python OpenCV image processing, lesson 52
- Introduction to python (III) network request and analysis
- China Merchants Bank credit card number recognition project (Part I), python OpenCV image processing journey, Part 53
- Introduction to python (IV) dynamic web page analysis and capture
- Python practice - capture 58 rental information and store it in MySQL database
- leetcode 119. Pascal's Triangle II(python)
- leetcode 31. Next Permutation(python)
- [algorithm learning] 807 Maintain the city skyline (Java / C / C + + / Python / go / trust)
- The rich woman's best friend asked me to write her a Taobao double 11 rush purchase script in Python, which can only be arranged
- Glom module of Python data analysis module (1)
- Python crawler actual combat, requests module, python realizes the full set of skin to capture the glory of the king
- Summarize some common mistakes of novices in Python development
- Python libraries you may not know
- [Python crawler] detailed explanation of selenium from introduction to actual combat [2]
- This is what you should do to quickly create a list in Python
- On the 55th day of the journey, python opencv perspective transformation front knowledge contour coordinate points
- Python OpenCV image area contour mark, which can be used to frame various small notes
- How to set up an asgi Django application with Postgres, nginx and uvicorn on Ubuntu 20.04
- Initial Python tuple
- Introduction to Python urllib module
- Advanced Python Basics: from functions to advanced magic methods
- Python Foundation: data structure summary
- Python Basics: from variables to exception handling
- Python notes (22): time module and calendar module