使用随机库在python3中交换list的元素

时间:2018-09-04 06:32:11

标签: python python-3.x sorting

使用随机库对列表进行排序,比方说数字列表_1。

导入python随机库的randint定义。

如何使用randint

2 个答案:

答案 0 :(得分:0)

import random
n=int(input())
list_1 = []
for i in range(n):
    list_1.append(int (input()))
list_2=[] 
while list_1:
    minimum = list_1[0]
    for x in list_1: 
        if x < minimum:
            minimum = x
    list_2.append(minimum)
    list_1.remove(minimum)    
sarr = [str(a) for a in list_2]
print(' '.join(sarr))

答案 1 :(得分:0)

对于您的问题的标题:

作为完整程序

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

Try it online!

作为匿名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

Try it online!

作为功能

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

Try it online!

对于您问题中的第一个问题:

您不能使用random模块对列表进行排序,因为它是针对随机函数而不是排序的。但是,您可以使用Python的sorted()函数对列表进行排序。

作为完整程序

print(sorted(eval(input())))

说明

print(                          Print out ...
      sorted(                   The sorted version of ...
             eval(              The evaluated version of ...
                  input()       The input
             )
      )
)

Try it online!

作为匿名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
         )

Try it online!