溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Python如何使用三元運(yùn)算符進(jìn)行條件賦值

發(fā)布時(shí)間:2022-03-11 09:41:20 來源:億速云 閱讀:336 作者:iii 欄目:編程語言

本篇內(nèi)容介紹了“Python如何使用三元運(yùn)算符進(jìn)行條件賦值”的有關(guān)知識(shí),在實(shí)際案例的操作過程中,不少人都會(huì)遇到這樣的困境,接下來就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!

Python如何使用三元運(yùn)算符進(jìn)行條件賦值

技巧1 就地交換兩個(gè)數(shù)字

Python 提供了一種在一行中進(jìn)行賦值和交換的直觀方式。請參考下面的例子。

x, y = 10, 20print(x, y)
 x, y = y, xprint(x, y)
 #1 (10, 20)#2 (20, 10)

右邊的賦值為一個(gè)新的元組播種。而左邊的立即將那個(gè)(未引用的)元組解包到名稱 <a><b>。

分配完成后,新元組將被取消引用并標(biāo)記為垃圾收集。變量的交換也發(fā)生在最終。


技巧2 比較運(yùn)算符的鏈接。

比較運(yùn)算符的聚合是另一個(gè)有時(shí)可以派上用場的技巧。

n = 10 result = 1 < n < 20 print(result) # True result = 1 > n <= 9 print(result) # False

技巧3 使用三元運(yùn)算符進(jìn)行條件賦值。

三元運(yùn)算符是 if-else 語句的快捷方式,也稱為條件運(yùn)算符。

[on_true] if [expression] else [on_false]

以下是一些示例,您可以使用它們使代碼緊湊簡潔。

下面的語句與它的意思相同,即“如果 y 為 9,則將 10 分配給 x,否則將 20 分配給 x ”。如果需要,我們可以擴(kuò)展運(yùn)算符的鏈接。

x = 10 if (y == 9) else 20

同樣,我們可以對類對象做同樣的事情。

x = (classA if y == 1 else classB)(param1, param2)

在上面的例子中,classA 和 classB 是兩個(gè)類,其中一個(gè)類構(gòu)造函數(shù)將被調(diào)用。

下面是一個(gè)沒有的例子。加入評估最小數(shù)字的條件。

def small(a, b, c):
	return a if a <= b and a <= c else (b if b <= a and b <= c else c)
	print(small(1, 0, 1))print(small(1, 2, 2))print(small(2, 2, 3))print(small(5, 4, 3))#Output#0 #1 #2 #3

我們甚至可以在列表推導(dǎo)式中使用三元運(yùn)算符。

[m**2 if m > 10 else m**4 for m in range(50)]#=> [0, 1, 16, 81, 256, 625, 1296, 2401, 4096, 6561, 10000, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400, 441, 484, 529, 576, 625, 676, 729, 784, 841, 900, 961, 1024, 1089, 1156, 1225, 1296, 1369, 1444, 1521, 1600, 1681, 1764, 1849, 1936, 2025, 2116, 2209, 2304, 2401]

技巧4 使用多行字符串

基本方法是使用從 C 語言派生的反斜杠。

multiStr = "select * from multi_row \
where row_id < 5"print(multiStr)# select * from multi_row where row_id < 5

另一個(gè)技巧是使用三引號(hào)。

multiStr = """select * from multi_row 
where row_id < 5"""print(multiStr)#select * from multi_row #where row_id < 5

上述方法的共同問題是缺乏適當(dāng)?shù)目s進(jìn)。如果我們嘗試縮進(jìn),它會(huì)在字符串中插入空格。

所以最終的解決方案是將字符串拆分成多行,并將整個(gè)字符串括在括號(hào)中。

multiStr= ("select * from multi_row ""where row_id < 5 ""order by age") print(multiStr)#select * from multi_row where row_id < 5 order by age

技巧5 將列表元素存儲(chǔ)到新變量中

我們可以使用一個(gè)列表來初始化一個(gè) no。的變量。在解壓列表時(shí),變量的數(shù)量不應(yīng)超過編號(hào)。列表中的元素。

testList = [1,2,3]x, y, z = testListprint(x, y, z)#-> 1 2 3

技巧6 打印導(dǎo)入模塊的文件路徑

如果您想知道代碼中導(dǎo)入的模塊的絕對位置,請使用以下技巧。

import threading 
import socketprint(threading)print(socket)#1- <module 'threading' from '/usr/lib/python2.7/threading.py'>#2- <module 'socket' from '/usr/lib/python2.7/socket.py'>

技巧7 使用交互式“_”運(yùn)算符

這是一個(gè)有用的功能,我們很多人都不知道。

在 Python 控制臺(tái)中,每當(dāng)我們測試表達(dá)式或調(diào)用函數(shù)時(shí),結(jié)果都會(huì)發(fā)送到臨時(shí)名稱 _(下劃線)。

>>> 2 + 13>>> _3>>> print _3

“_”引用上次執(zhí)行的表達(dá)式的輸出。


技巧8 字典/集合理解

就像我們使用列表推導(dǎo)一樣,我們也可以使用字典/集合推導(dǎo)。它們易于使用且同樣有效。這是一個(gè)例子。

testDict = {i: i * i for i in xrange(10)} testSet = {i * 2 for i in xrange(10)}print(testSet)print(testDict)
#set([0, 2, 4, 6, 8, 10, 12, 14, 16, 18])
#{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}

注意 -兩個(gè)語句中只有 <:> 的區(qū)別。此外,要在 Python3 中運(yùn)行上述代碼,請將 替換為 。


技巧9 調(diào)試腳本

我們可以在 模塊的幫助下在 Python 腳本中設(shè)置斷點(diǎn)。請按照以下示例進(jìn)行操作。

import pdb
pdb.set_trace()

我們可以在腳本的任何地方指定 <pdb.set_trace()> 并在那里設(shè)置斷點(diǎn)。這是非常方便的。


技巧10 設(shè)置文件共享

Python 允許運(yùn)行 HTTP 服務(wù)器,您可以使用它從服務(wù)器根目錄共享文件。下面是啟動(dòng)服務(wù)器的命令。

Python 2

python -m SimpleHTTPServer

Python 3

python3 -m http.server

以上命令將在默認(rèn)端口 8000 上啟動(dòng)服務(wù)器。您還可以通過將自定義端口作為最后一個(gè)參數(shù)傳遞給上述命令來使用自定義端口。


技巧11 在 Python 中檢查對象

我們可以通過調(diào)用 dir() 方法來檢查 Python 中的對象。這是一個(gè)簡單的例子。

test = [1, 3, 5, 7]print( dir(test) )
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

技巧12 簡化 if 語句

要驗(yàn)證多個(gè)值,我們可以通過以下方式進(jìn)行。

if m in [1,3,5,7]:

代替:

if m==1 or m==3 or m==5 or m==7:

或者,我們可以使用 ‘{1,3,5,7}’ 而不是 ‘[1,3,5,7]’ 作為 ‘in’ 運(yùn)算符,因?yàn)?‘set’ 可以通過 O(1) 訪問每個(gè)元素。


技巧13 在運(yùn)行時(shí)檢測 Python 版本

有時(shí),如果當(dāng)前運(yùn)行的 Python 引擎低于支持的版本,我們可能不想執(zhí)行我們的程序。為此,您可以使用以下代碼片段。它還以可讀格式打印當(dāng)前使用的 Python 版本。

import sys#Detect the Python version currently in use.if not hasattr(sys, "hexversion") or sys.hexversion != 50660080:
    print("Sorry, you aren't running on Python 3.5\n")
    print("Please upgrade to 3.5.\n")
    sys.exit(1)
    #Print Python version in a readable format.print("Current Python version: ", sys.version)

或者,您可以在上面的代碼中使用sys.version_info >= (3, 5)替換sys.hexversion!= 50660080。這是一位知情讀者的建議。

在 Python 2.7 上運(yùn)行時(shí)的輸出。

Python 2.7.10 (default, Jul 14 2015, 19:46:27)[GCC 4.8.2] on linux
   
Sorry, you aren't running on Python 3.5Please upgrade to 3.5.

在 Python 3.5 上運(yùn)行時(shí)的輸出。

Python 3.5.1 (default, Dec 2015, 13:05:11)[GCC 4.8.2] on linux
   
Current Python version:  3.5.2 (default, Aug 22 2016, 21:11:05) [GCC 5.3.0]

技巧14 組合多個(gè)字符串

如果您想連接列表中所有可用的標(biāo)記,請參見以下示例。

>>> test = ['I', 'Like', 'Python', 'automation']

現(xiàn)在,讓我們從上面給出的列表中的元素創(chuàng)建一個(gè)字符串。

>>> print ''.join(test)

技巧15 反轉(zhuǎn) string/list 的四種方法

反轉(zhuǎn)列表本身

testList = [1, 3, 5]testList.reverse()print(testList)#-> [5, 3, 1]

在循環(huán)中迭代時(shí)反轉(zhuǎn)

for element in reversed([1,3,5]): print(element)#1-> 5#2-> 3#3-> 1

反轉(zhuǎn)一個(gè)字符串

"Test Python"[::-1]

這使輸出為“nohtyP tseT”

使用切片反轉(zhuǎn)列表

[1, 3, 5][::-1]

上面的命令將輸出 [5, 3, 1]。


技巧16 玩枚舉

使用枚舉器,在循環(huán)中很容易找到索引。

testlist = [10, 20, 30]for i, value in enumerate(testlist):
	print(i, ': ', value)#1-> 0 : 10#2-> 1 : 20#3-> 2 : 30

技巧17 在 Python 中使用枚舉。

我們可以使用以下方法來創(chuàng)建枚舉定義。

class Shapes:
	Circle, Square, Triangle, Quadrangle = range(4)print(Shapes.Circle)print(Shapes.Square)print(Shapes.Triangle)print(Shapes.Quadrangle)#1-> 0#2-> 1#3-> 2#4-> 3

技巧18 從函數(shù)返回多個(gè)值。

支持此功能的編程語言并不多。但是,Python 中的函數(shù)確實(shí)會(huì)返回多個(gè)值。

請參考以下示例以查看它的工作情況。

# function returning multiple values.def x():
	return 1, 2, 3, 4# Calling the above function.a, b, c, d = x()print(a, b, c, d)

#-> 1 2 3 4


技巧19 使用 splat 運(yùn)算符解包函數(shù)參數(shù)。

splat 運(yùn)算符提供了一種解壓參數(shù)列表的藝術(shù)方式。為清楚起見,請參閱以下示例。

def test(x, y, z):
	print(x, y, z)testDict = {'x': 1, 'y': 2, 'z': 3} testList = [10, 20, 30]test(*testDict)test(**testDict)test(*testList)#1-> x y z#2-> 1 2 3#3-> 10 20 30

技巧20 使用字典來存儲(chǔ) switch。

我們可以制作一個(gè)字典存儲(chǔ)表達(dá)式。

stdcalc = {
	'sum': lambda x, y: x + y,
	'subtract': lambda x, y: x - y}print(stdcalc['sum'](9,3))print(stdcalc['subtract'](9,3))#1-> 12#2-> 6

技巧21 計(jì)算一行中任意數(shù)字的階乘。

Python 2.x.

result = (lambda k: reduce(int.__mul__, range(1,k+1),1))(3)print(result)#-> 6

Python 3.x.

import functools
result = (lambda k: functools.reduce(int.__mul__, range(1,k+1),1))(3)print(result)

#-> 6


技巧22 查找列表中出現(xiàn)頻率最高的值。

test = [1,2,3,4,2,2,3,1,4,4,4]print(max(set(test), key=test.count))#-> 4

技巧23 重置遞歸限制。

Python 將遞歸限制限制為 1000。我們可以重置它的值。

import sys

x=1001print(sys.getrecursionlimit())sys.setrecursionlimit(x)print(sys.getrecursionlimit())#1-> 1000#2-> 1001

請僅在需要時(shí)應(yīng)用上述技巧。


技巧24 檢查對象的內(nèi)存使用情況。

在 Python 2.7 中,32 位整數(shù)消耗 24 字節(jié),而在 Python 3.5 中使用 28 字節(jié)。為了驗(yàn)證內(nèi)存使用情況,我們可以調(diào)用 方法。

Python 2.7.

import sys
x=1print(sys.getsizeof(x))#-> 24

Python 3.5.

import sys
x=1print(sys.getsizeof(x))#-> 28

技巧25 使用 __slots__ 減少內(nèi)存開銷。

你有沒有觀察到你的 Python 應(yīng)用程序消耗了大量資源,尤其是內(nèi)存?這是使用<__slots__>類變量在一定程度上減少內(nèi)存開銷的一種技巧。

import sysclass FileSystem(object):

	def __init__(self, files, folders, devices):
		self.files = files
		self.folders = folders
		self.devices = devicesprint(sys.getsizeof( FileSystem ))class FileSystem1(object):

	__slots__ = ['files', 'folders', 'devices']
	
	def __init__(self, files, folders, devices):
		self.files = files
		self.folders = folders
		self.devices = devicesprint(sys.getsizeof( FileSystem1 ))#In Python 3.5#1-> 1016#2-> 888

顯然,您可以從結(jié)果中看到內(nèi)存使用量有所節(jié)省。但是當(dāng)一個(gè)類的內(nèi)存開銷不必要地大時(shí),你應(yīng)該使用 __slots__ 。僅在分析應(yīng)用程序后執(zhí)行此操作。否則,您將使代碼難以更改并且沒有真正的好處。


技巧26 Lambda 模仿打印功能。

import sys
lprint=lambda *args:sys.stdout.write(" ".join(map(str,args)))lprint("python", "tips",1000,1001)#-> python tips 1000 1001

技巧27 從兩個(gè)相關(guān)序列創(chuàng)建字典。

t1 = (1, 2, 3)t2 = (10, 20, 30)print(dict (zip(t1,t2)))#-> {1: 10, 2: 20, 3: 30}

技巧28 在線搜索字符串中的多個(gè)前綴。

print("http://www.baidu.com".startswith(("http://", "https://")))print("https://juejin.cn".endswith((".com", ".cn")))#1-> True#2-> True

技巧29 形成一個(gè)統(tǒng)一的列表,不使用任何循環(huán)。

import itertools
test = [[-1, -2], [30, 40], [25, 35]]print(list(itertools.chain.from_iterable(test)))#-> [-1, -2, 30, 40, 25, 35]

如果您有一個(gè)包含嵌套列表或元組作為元素的輸入列表,請使用以下技巧。但是,這里的限制是它使用了 for 循環(huán)。

def unifylist(l_input, l_target):
    for it in l_input:
        if isinstance(it, list):
            unifylist(it, l_target)
        elif isinstance(it, tuple):
            unifylist(list(it), l_target)
        else:
            l_target.append(it)
    return l_target

test =  [[-1, -2], [1,2,3, [4,(5,[6,7])]], (30, 40), [25, 35]]print(unifylist(test,[]))#Output => [-1, -2, 1, 2, 3, 4, 5, 6, 7, 30, 40, 25, 35]

統(tǒng)一包含列表和元組的列表的另一種更簡單的方法是使用 Python 的 < more_itertools > 包。它不需要循環(huán)。只需執(zhí)行 < pip install more_itertools >,如果還沒有的話。

import more_itertools

test = [[-1, -2], [1, 2, 3, [4, (5, [6, 7])]], (30, 40), [25, 35]]print(list(more_itertools.collapse(test)))#Output=> [-1, -2, 1, 2, 3, 4, 5, 6, 7, 30, 40, 25, 35]

技巧30 在 Python 中實(shí)現(xiàn)真正的 switch-case 語句。

這是使用字典來模仿 switch-case 構(gòu)造的代碼。

def xswitch(x): 
	return xswitch._system_dict.get(x, None) xswitch._system_dict = {'files': 10, 'folders': 5, 'devices': 2}print(xswitch('default'))print(xswitch('devices'))#1-> None#2-> 2

“Python如何使用三元運(yùn)算符進(jìn)行條件賦值”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識(shí)可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實(shí)用文章!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI