Python 條件表示式

2022-03-07 12:36:15 字數 1330 閱讀 3687

import os

import re

mask = re.compile('.+fna$') # $說明從後開始匹配

# 最好先看一下當前路徑是什麼

os. getcwd()

# 獲得資料夾裡面所以檔名

file_names= os.listdir()

# 或者隨便用個例子

file_names = ['1.fna', '1.fna.nsq', '1.fna.nsi',]

# 方法1 for迴圈,遍歷每個檔名,返回fna結尾的檔案(事先知道只有乙個)

for db in file_names:

if mask.match(db):

path = db

path

# 方法2 方法1用條件表示式寫出來

path = [db for db in file_names if mask.match(db)] # 注意[ ]不能少

path

# 方法3 filter 函式

path = list(filter(mask.match, file_names))[0]

path

# 以上三個path都會是1.fna

# 把這個和當前的目錄組合起來就是資料庫所在的路徑

print(os.path.join(os.getcwd(),path))

搜問題的時候看到了第二種寫法,覺得挺有趣的,就稍微看了下。

a, b, c = 1, 2, 3

# 1.常規

if a>b:

c = a

else:

c = b

# 2.表示式

c = a if a>b else b # 先執行中間的if,如果返回true,就是左邊,false是右邊。

# 3.二維列表

c = [b,a][a>b] #實際是[b,a][false],因為false被轉換為0,所以是[1,2][0],也就是[1]

# false返回第乙個,true 返回第乙個。

# 4c = (a>b and [a] or [b])[0]

# 這個比較好玩,false and [1] or [2],因為and的優先順序高於or,先算and

# false和[1] and之後還是false,和[2]or之後卻成了[2]

# true 和[1] and之後是[1],[1]和[2]or結果是[1]

# 也就是false和true在和別人做boolean運算的時候,根據and還是or,f和t在前在後有不一樣的資料轉換規則。

python關於條件表示式的說明 pep308

python 條件表示式學習

與 and 或 or 非 not rfind 用法 返回值是查詢到的目標字元在原字串中的下標,如果沒找到返回 1,如果在第0個位置找到返回0,其他的數字。錯誤例項 rule suffix ls rule.rfind pre 1not rule.rfind pre false rule.rfind p...

Python 三元表示式(條件表示式)

使用一行 快速判斷,替換複雜的多行if語句,使得 簡單可維護。如果條件為真,返回真,否則返回假 condition is true if condition else condition is false is fat true state fat if is fat else not fat 返回...

python基礎之條件表示式

分支語句 score 98if score 90 print 優秀 elif score 80 print 不錯 elif score 60 print 及格 else print 不及格 a input 請輸入乙個數字 input 函式,從鍵盤讀取使用者的輸入,a是返回值,是字串型別 ifnot ...