python - python3中使用随机库交换list的元素
问题描述
使用随机库对列表进行排序,假设 list_1 的数字按升序排列。
导入python随机库的randint定义。
如何使用 randint
解决方案
对于您的问题标题:
作为一个完整的程序
from random import sample
print(sample((s:=eval(input())),len(s)))
解释
from random import sample Imports the sample function only in order to preserve speed.
print( Print out ...
sample( Shuffle randomly this list...
(s:= Python 3.8's assignment eval (assign to s while still evaling)
eval(input()) Evalulate the input, which is a Python list
),
len( Take the length of ...
s the input
)
)
)
作为匿名 lambda
lambda x:sample(x, len(x))
from random import sample
解释
lambda x: Define a lambda that takes in one argument named x
sample( Shuffle randomly
x, The one argument, which is a list
len( The length of ...
x The one argument, which is a list
)
)
from random import sample Import the sample function
作为一个函数
def e(x):return sample(x, len(x))
from random import sample
解释
def e(x): Define a function named e with one argument named x
return Set the functions value to be ...
sample( Shuffle a list
x, The one argument, which is a list
len( Length of ...
x The one argument; x
)
)
from random import sample Import the sample function
对于问题正文中的第一个问题:
您不能使用该random
模块对列表进行排序,因为它用于随机函数,而不是用于排序。但是,您可以使用 Python 的sorted()
函数来对列表进行排序。
作为一个完整的程序
print(sorted(eval(input())))
解释
print( Print out ...
sorted( The sorted version of ...
eval( The evaluated version of ...
input() The input
)
)
)
作为匿名 lambda
lambda x:sorted(x)
解释
lambda x: Declare a lambda with one argument, x
sorted( Return the sorted value of...
x The lambda's argument
)