程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python comprehension and ternary operator

編輯:Python

列表推導式

List comprehensions simplify list looping

  • 格式表達式 for 變量 in 列表 [if 條件語句](The content in square brackets can be omitted)
  • 使用方式
"""Quickly generate an include1-20數字的列表"""
list1 = [i for i in range(1,21)]
"""Quickly generate an include1-20之間能被3Divisible list of all numbers"""
list2 = [i for i in range(1,21) if i%3==0]
"""Quickly generate an include1-20之間能被3List of squares of all numbers that are divisible"""
list3 = [i*i for i in range(1,21) if i%3==0]
  • 替代for循環和filter函數:Filter out all even numbers in the list
test = [1,2,3,4,5,6,7,8,9,10]
"""Use a normal loop"""
list1 = []
for i in test:
if i%2==0:
list1.append(i)
"""使用filter"""
list2 = list(filter(lambda i:i%2==0,test))
"""使用列表推導式"""
list3 = [i for i in test if i%2==0]
  • 替代for循環和map函數:Converts all strings in the list to integers
test = ["1","2","3","4","5","6","7","8","9","10"]
"""Use a normal loop"""
list1 = []
for i in test:
list1.append(int(i))
"""使用filter"""
list2 = list(map(lambda i:int(i),test))
"""使用列表推導式"""
list3 = [int(i) for i in test]
  • 注意:List comprehensions work for single-level loops,When there are two or more layers of loops, using the derivation will be counterproductive,Although the code is simplified,But it will make the content of the simplified code obscure and difficult to understand,結構也不清晰,Very inappropriate to read and modify.
"""Use a normal loop"""
list1 = []
for i in range(1,5):
for j in range(1,i):
if j%2 == 0:
list1.append((i,j))
"""使用列表推導式"""
list2 = [(i,j) for i in range(1,5) for j in range(1,i) if j%2==0]

字典推導式

Dictionary comprehensions simplify dictionary loops

  • 格式:{v: k for k, v in 字典 [if 條件語句]} (The content in square brackets can be omitted)
  • 舉例1:將字典中keyValues ​​are converted to uppercase
test = {
"a":5,"B":10,"c":15,"D":20}
"""Use a normal loop"""
dict1 = {
}
for k,v in test.items():
dict1[k.upper()] = v
"""使用字典推導式"""
dict2 = {
k.upper():v for k,v in test.items()}
  • 舉例2:Filter out all in the dictionaryvalue是偶數的鍵值對
test = {
"a":5,"B":10,"c":15,"D":20}
"""Use a normal loop"""
dict1 = {
}
for k,v in test.items():
if v%2==0:
dict1[k] = v
"""使用字典推導式"""
dict2 = {
k:v for k,v in test.items() if v%2==0}

三目運算符

The ternary operator can simplify selection

  • 格式:exp1 if 條件語句 else exp2

  • 運行過程:if the conditional statement is true,just execute and returnexp1,Otherwise, execute and return exp2

"""簡化前"""
if a>b:
max = a;
else:
max = b;
"""簡化後"""
max = a if a>b else b

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved