创建一个随机整数列表,然后将所有相同的数字放在彼此旁边

问题描述 投票:0回答:4
def run():
    lst=[]
    for i in range(0,20):
        ran = random.randint(1,10)
        lst.append(ran)
return lst

到目前为止,我已经创建了一个从1到9的随机整数列表,其中包含20个值,但是如何合并交换方法以使相同但不相邻的值彼此相邻?

谢谢

python for-loop random
4个回答
0
投票
import random

#this is the function you gave with little edits, to see the changes it make
# after the process

def run():
    lst=[]
    for i in range(0,20):
        ran = random.randint(1,10)
        lst.append(ran)
    print(lst)
    swap(lst)
    print(lst)
    return lst

#this uses indexes of every element, and checks every other element of the list.
#this swap function works for lists with element made up of strings as well.

def swap(lst):
    for i in range(len(lst)):
        nu_m=lst[i]
        x=i+1
        while x<len(lst):
            dump=i+1
            acc=lst[i+1]
            if(lst[i]==lst[x]):
                lst[dump]=lst[x]
                lst[x]=acc
            x=x+1
x=run()

2
投票

您可以使用key参数的索引构建自己的排序条件。

import random

def run():
    lst=[]
    for i in range(0,20):
        ran = random.randint(1,10)
        lst.append(ran)
    return lst

lst = run()
print(lst) 
#[5, 10, 5, 1, 8, 10, 10, 6, 4, 9, 3, 9, 6, 9, 2, 9, 9, 1, 7, 8]
result = sorted(lst, key = lambda x: lst.index(x))
print(result)
#[5, 5, 10, 10, 10, 1, 1, 8, 8, 6, 6, 4, 9, 9, 9, 9, 9, 3, 2, 7]

1
投票

也许只是排序列表:

lst = sorted(lst)


0
投票

首先让我们创建另一个列表以保持唯一数字的顺序(如set,但未排序)。

unsorted_set = []
for nb in lst:
    if nb not in unsorted_set:
        unsorted_set.append(nb)

现在我们得到了这个列表,让我们创建一个将继续该列表的最终列表,但每个数字将重复n次,n是第一个列表中数字的出现。我们将用lst.count()做到这一点

final_list = []
for nb in unsorted_set: 
    for _ in range(lst.count(nb)):
        final_list.append(nb)

请注意,使用List Comprehension可以简化此代码。

© www.soinside.com 2019 - 2024. All rights reserved.