簡體   English   中英

str 的 .index 方法如何在 python 中工作?

[英]How does .index method of str work in python?

這段代碼是如何工作的?

values = ['1', '3', '9', '6', '7']  # just an example of what comes in
index = "123456789"["8" in values:].index  # everything except this line is understandable
print(sorted(values, key=index))

這種代碼對我來說看起來很奇怪,所以我不明白它是如何工作的。

str[str in list:].index

這是不必要的復雜代碼。 要么有人做錯了什么,要么他們想變得聰明。 這是該行的含義:

index = "123456789"["8" in values:].index

"8" in values"8" in values開始。 這評估為False ,因為"8"不在values列表中。 這與:

index = "123456789"[False:].index

由於False計算結果為0 ,因此與以下內容相同:

index = "123456789"[0:].index

並且因為[0:]是指整個字符串,所以:

index = "123456789".index

將變量index為指向字符串"123456789".index()方法。 然后這被用作密鑰來sorted()其具有分選的效果values基於每個值在索引"123456789"的字符串。

最后,這與以下內容相同:

print(sorted(values))

index = "123456789"["8" in values:].index # everything except this line is understandable

那條線上發生了幾件事,我們可以將其分成多行以了解正在發生的事情:

values = ['1', '3', '9', '6', '7']  # just an example of what comes in
boolean = ("8" in values)
numbers = "123456789"[boolean:]
index = numbers.index  # everything except this line is understandable
print(sorted(values, key=index))

讓我們從"8" in values開始,這會產生一個布爾輸出,它是False因為values列表中沒有8

現在我們有了"123456789"[False:]在 python 中,字符串可以像帶 [] 括號的數組一樣訪問。

讓我們仔細看看那個冒號,因為它看起來也很混亂。 冒號在 python 中也用於切片,當它放在索引的右側時,它指定了該索引之后的所有內容,包括索引。

但是等一下,False 還不是一個數字。 是的,python 將 False 轉換為 0,所以作為最終結果,我們有"123456789"[0:] 所以這個復雜的代碼對我們沒有任何作用,因為它只返回整個字符串"123456789"

現在我們在index = numbers.index ,實際上是index = "123456789".index 這存儲了字符串"123456789"的索引方法。

這用於 sorted 方法。

https://docs.python.org/3/howto/sorting.html#key-functions指出“key 參數的值應該是一個函數(或其他可調用的),它接受一個參數並返回一個鍵用於排序的目的。”

這將為值中的每個數字調用“123456789”.index(number),並使用返回的索引提供如下排序:

讓我們回顧一下values = ['1', '3', '9', '6', '7']"123456789"

"123456789".index('1') # Gives 0 (because the index of '1' in `"123456789"` is 0)  
"123456789".index('3') # Gives 2 (because the index of '3' in `"123456789"` is 2)  
"123456789".index('9') # Gives 8  
"123456789".index('6') # Gives 5  
"123456789".index('7') # Gives 6  

現在它使用這些數字並將它們從最小到最大 (0,2,5,6,8) 排序,並顯示values = ['1', '3', '9', '6', '7']按此順序。 (0 對應於“1”,因此先行,2 對應於“3”,5 對應於“6”,依此類推。)

結論

values = ['1', '3', '9', '6', '7']  # just an example of what comes in
index = "123456789"["8" in values:].index  # everything except this line is understandable
print(sorted(values, key=index))

這段代碼使用了一種非常復雜的方法來對數字字符串列表進行排序。 下面是一種更清晰的方法,適用於數字超過 1-9 的列表。

推薦(適用於所有整數):

values = ['1', '3', '9', '6', '7']  # just an example of what comes in
print(sorted(values, key=int))

它是如何工作的? int函數首先將 values 中的每個元素轉換為作為sorted key函數提供的整數。 當python收到要排序的數字時,它會自動將它們從最小到最大排序。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM