简体   繁体   English

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

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

How does this code work?这段代码是如何工作的?

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))

this kind of code looks very strange to me so i don't understand how it works.这种代码对我来说看起来很奇怪,所以我不明白它是如何工作的。

str[str in list:].index

This is needlessly complicated code.这是不必要的复杂代码。 Either someone did something incorrectly, or they're trying to be clever.要么有人做错了什么,要么他们想变得聪明。 Here's what that line means:这是该行的含义:

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

Start with the "8" in values ."8" in values"8" in values开始。 This evaluates to False , because "8" is not in the values list.这评估为False ,因为"8"不在values列表中。 This is the same as:这与:

index = "123456789"[False:].index

which, because False evaluates to 0 , is just the same as:由于False计算结果为0 ,因此与以下内容相同:

index = "123456789"[0:].index

and because [0:] refers to the entire string, this:并且因为[0:]是指整个字符串,所以:

index = "123456789".index

sets the variable index to point to the .index() method of the string "123456789" .将变量index为指向字符串"123456789".index()方法。 This is then used as the key to sorted() which has the effect of sorting values based on the index of each value in the "123456789" string.然后这被用作密钥来sorted()其具有分选的效果values基于每个值在索引"123456789"的字符串。

In the end, this is the same as:最后,这与以下内容相同:

print(sorted(values))

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

There are a couple things happening on that line and we can split it into multiple lines to understand what is happening:那条线上发生了几件事,我们可以将其分成多行以了解正在发生的事情:

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))

Let's start with "8" in values this produces a boolean output which is False because there is no 8 in the values list.让我们从"8" in values开始,这会产生一个布尔输出,它是False因为values列表中没有8

Now we have "123456789"[False:] In python strings can be accessed like an array with [ ] brackets.现在我们有了"123456789"[False:]在 python 中,字符串可以像带 [] 括号的数组一样访问。

Let's take a closer look at that colon because that may look confusing as well.让我们仔细看看那个冒号,因为它看起来也很混乱。 The colon is also used in python for slicing and when its placed on the right side of an index, it specifies everything after that index including the index.冒号在 python 中也用于切片,当它放在索引的右侧时,它指定了该索引之后的所有内容,包括索引。

But hang on, False isn't a number yet.但是等一下,False 还不是一个数字。 Right, python converts False to 0 so as a final result we have "123456789"[0:] .是的,python 将 False 转换为 0,所以作为最终结果,我们有"123456789"[0:] So this complicated code does nothing for us because it just returns the entire string "123456789" .所以这个复杂的代码对我们没有任何作用,因为它只返回整个字符串"123456789"

Now we are at index = numbers.index , which is really index = "123456789".index .现在我们在index = numbers.index ,实际上是index = "123456789".index This stores the index method of the string "123456789" .这存储了字符串"123456789"的索引方法。

This is used in the sorted method.这用于 sorted 方法。

https://docs.python.org/3/howto/sorting.html#key-functions states "The value of the key parameter should be a function (or other callable) that takes a single argument and returns a key to use for sorting purposes." https://docs.python.org/3/howto/sorting.html#key-functions指出“key 参数的值应该是一个函数(或其他可调用的),它接受一个参数并返回一个键用于排序的目的。”

This will call "123456789".index(number) for every number in values, and use the returned index to provide the sorting like this:这将为值中的每个数字调用“123456789”.index(number),并使用返回的索引提供如下排序:

Let's recap values = ['1', '3', '9', '6', '7'] and "123456789"让我们回顾一下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  

Now it uses these numbers and sorts them from least to greatest (0,2,5,6,8) and presents the values from values = ['1', '3', '9', '6', '7'] in that order.现在它使用这些数字并将它们从最小到最大 (0,2,5,6,8) 排序,并显示values = ['1', '3', '9', '6', '7']按此顺序。 (0 corresponded to '1' so that goes first, 2 corresponded to '3', 5 corresponded to '6' and so on.) (0 对应于“1”,因此先行,2 对应于“3”,5 对应于“6”,依此类推。)

Conclusion结论

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))

This code used a very complicated way to sort the list of numerical strings.这段代码使用了一种非常复杂的方法来对数字字符串列表进行排序。 Below is a more clear way of doing it that will work for lists that have numbers that exceed 1-9.下面是一种更清晰的方法,适用于数字超过 1-9 的列表。

Recommended (works for all integers):推荐(适用于所有整数):

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

How does it work?它是如何工作的? The int function first converts each element in values to an integer as provided as a key function to sorted . int函数首先将 values 中的每个元素转换为作为sorted key函数提供的整数。 When python receives numbers to sort it will automatically sort them from least to greatest.当python收到要排序的数字时,它会自动将它们从最小到最大排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM