繁体   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