current position:Home>[reprint] Python - list comprehension
[reprint] Python - list comprehension
2022-08-06 07:36:57【ShaderJoy】
版权声明:本文为CSDN博主「那一定会很酷」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明.
原文链接:blog.csdn.net/weixin_5227…
Python 列表推导式
一.Why learn list comprehensions 母鸡啊
- List comprehensions can be said in PythonIt is widely used in program development.
- List comprehensions can be used in a very concise way to quickly generate lists that satisfy specific needs,And the code is very readable.
- Python的内部实现对列表推导式做了大量优化,Can guarantee fast running speed.
二.Start learning about list comprehensions 快醒醒
语法
[表达式 for 变量 in 序列或迭代对象]
列表推导式在逻辑上相当于一个循环,But the form is more concise
具体操作:
① 简单举例
>>> list = [x*x for x in range(10)]
>>> print(list)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> print(sum(list))
285
复制代码
② 使用列表推导式实现嵌套列表的平铺
>>> vec = [[1,2,3],[4,5,6],[7,8,9]]
>>> list = [num for elem in vec for num in elem]
>>> print(list)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
''' 在这个列表推导式中有两个循环,其中第一个循环为外循环,执行得慢; 第二个循环为内循环,执行得快. '''
#用循环实现其等价写法:
vec = [[1,2,3],[4,5,6],[7,8,9]]
result= []
for elem in vec:
for num in elem:
result.append(num)
print(result)
复制代码
③ 过滤不符合条件的元素
在列表推导式中可以使用 if
子句来进行筛选,只在结果列表中保留符合条件的元素.
>>> list = [1,2,3,45,6,7,7,8,90,22]
>>> list = [i for i in list if i >10] #if条件判断
>>> list
[45, 90, 22]
>>> list = [x*x if x%2 != 0 else x for x in[1,2,3,4,5]] #if-else条件判断
>>> list
[1, 2, 9, 4, 25]
#List of known grades to find the highest scoring students
scores = {'zhangsan':11,"lisi":22,"wanngwu":33}
highest = max(scores.values())
highestperson = [name for name,score in scores.items() if score == highest]
print(highestperson)
#Use a list comprehension to find the position of the largest element in a list
>>> from random import randint
>>> x = [randint(1,10) for i in range(10)]#randint(1,10)是在1-10之间随机生成一个数,后面range(10)The role is to cycle10次
>>> x
[2, 6, 5, 9, 7, 4, 8, 3, 1, 5]
>>> m = max(x)
>>> m
9
>>> index_l = [index for index,value in enumerate(x) if value == m]
>>> index_l
[3]
复制代码
④ 使用多个循环实现多序列元素的任意组合
>>> l = [(x,y) for x in[1,2,3] for y in[3,2,4] if x != y]
>>> l
[(1, 3), (1, 2), (1, 4), (2, 3), (2, 4), (3, 2), (3, 4)]
''' 对于包含多个循环的列表推导式,Be sure to understand the execution order or nesting relationship of multiple loops '''
复制代码
⑤ 使用列表推导式实现矩阵转置
>>> matrix = [[1,2,3],[4,5,6],[7,8,9]]
>>> re_matrix = [[row[i] for row in matrix]for i in range(3)]
>>> re_matrix
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
复制代码
⑥ 列表推导式中可以使用函数或复杂表达式
def f(v):
if v%2 == 0:
v *= 2
else:
v += 1
return v
print([f(v) for v in [-1,0,1,2,3] if v > 0])
print([v*2 if v%2==0 else v+1 for v in [-1,0,1,2,3] if v > 0])
复制代码
⑦ 列表推导式支持文件对象迭代
>>> fp = open("D:\各种文件\课程设计\Zhengzhou's 14th Five-Year Plan.txt",'r',encoding = 'utf-8')
>>> print([line for line in fp])
#Read result is too long,省略
>>> fp.close()
复制代码
三. Ask a simple question to practice
应用1:使用列表推导式生成 100 以内的所有素数
要求:One line of code kills it!
>>> import math
>>> l = [p for p in range(2,100) if 0 not in[p%d for d in range(2, int(math.sqrt(p))+1)]]
>>> l
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
复制代码
I'm not cheating,The core code is indeed one line(傲娇 )
应用2:实现矩阵转置
matrix = [[1, 2, 3, 4],[5, 6, 7, 8],[9, 10, 11, 12]]
print("原矩阵:",matrix)
print("转置矩阵为:",[[row[i] for row in matrix] for i in range(4)])
复制代码
copyright notice
author[ShaderJoy],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/218/202208060733407360.html
The sidebar is recommended
- Get the input and output information of the onnx model Python script
- Common parameters of python matplotlib and drawing examples
- python axessubplot_ use matplotlib's savefig to save plots generated from python pandas (AxesSubPlot)
- Qixi Festival_A Python program that moves the mouse to play the confession balloon (available in August 2022)
- Python knowledge points: Python variables, data types
- Python open virtual environment
- Python uses Hive to query data
- python+opencv study notes
- python--log processing logging.handlers.TimedRotatingFileHandler
- The problem that yum is unavailable after python upgrade
guess what you like
Application of bubbling method in program thought in advanced scl programming in python and 1200PLC
Tensorflow C++ deployment practice - python environment establishment on linux platform (2)
Python graduation design works based on django framework personal blog system completed finished product (7) mid-term inspection report
Python graduation design works based on django framework personal blog system completed design (8) graduation design thesis template
Python graduation design works are based on the django framework enterprise company website. The finished product (1) Development overview
Application of bubbling method in program thought in advanced scl programming in python and 1200PLC
python get all characters before or after a specified character
[Python | Word Cloud] Draw a super beautiful word cloud from chat records (Happy Qixi Festival, classmate Zeng)
Python data visualization-----make a global earthquake scatter plot
Python. Iterator object iter() (Based on the iterator feature, dismantle the complicated single-line "forced code", and understand the "secret method" for selecting fixed-length elements of the sequence.)
Random recommended
- Python's common modules of threading and Thread modules The first stage of thread implementation
- Blender Python Programming: Creating Emitting Materials
- Python multiprocessing
- How does python implement image edge detection
- Django paging method
- django regex
- How does Python represent time?2 modules, 3 ways, 1 text to understand~
- Modify column name and row index in pandas DataFrame
- [python pandas groupby]
- Python Daily Practice (New Question Bank of Niu Ke) - Day 20: Dictionary Practice
- [LeetCode brush questions] Hash table - some questions are implemented with built-in functions (with Python code)
- [LeetCode brush questions] Linked list topic (1) (with Python code)
- [Small case of python learning] Simulation system invasion to enhance interest
- Getting Started with Python Basics - Essential Knowledge for Getting Started
- How does Python represent time?2 modules, 3 ways, 1 text to get it~
- Python office software automation, master openpyxl operation in 5 minutes
- Introduction to Python Basics - Variables, Strings
- [python2] remove the u in front of the unicode string
- How to use the Python Color class to draw text
- How to use Asyncio Python web programming
- 27 Python artificial intelligence libraries have been sorted out, it is recommended to collect!
- [Python] Word2Vec predicts what will be left if I subtract 'love' from my 'life'
- When I export a pandas package, there is a problem. If I don't import it, there is no problem. Is this not enough memory?
- Python version 3.7.4 How can I install locust successfully?
- How does python use pyinstaller to package music into exe, that is, play background music when running the packaged program?
- Python use pyinstaller how to wrap up music exe, is to run a packaged program play background music?
- Rescue 007 of graph traversal application, detailed analysis of python version
- 27 Python artificial intelligence libraries have been sorted out, it is recommended to collect~
- pandas DataFrame data filtering (2)
- Python is how to represent time?- two modules, three ways, complete the ~ 1
- The definition of pycharm writing python code
- Problems defining functions in Python
- Python Socket Network Programming
- Django server running error
- Python image processing notes - image matching based on Harris corners (skimage)
- (Thirteen--1) Concurrent programming of python (thread, queue, process, coroutine, process thread coroutine comparison)
- (12) Python's memory management mechanism
- Python crawler entry case day07: Hippopx
- Django reports an error ModuleNotFoundError: No module named 'mysqlclient'
- Python study notes