这段代码是如何工作的?
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
开始。计算结果为False
,因为"8"
不在values
列表中。这相当于:
index = "123456789"[False:].index
,因为False
求值为0
,所以与
index = "123456789"[0:].index
,因为[0:]
指向整个字符串,所以:
index = "123456789".index
设置变量index
指向字符串"123456789"
的.index()
方法。然后,它被用作sorted()
的键,它的作用是根据"123456789"
字符串中每个值的索引对values
进行排序。
最后,这与:
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形参的值应该是一个函数(或其他可调用对象),它接受一个参数并返回一个用于排序的键。">
这将为values中的每个数字调用"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中的每个元素转换为整数,就像key
函数向sorted
提供的那样。当python接收到要排序的数字时,它会自动将它们从最小到最大排序。