【问题标题】:Create a list of random integers and then put all numbers that are the same right beside eachother创建一个随机整数列表,然后将所有相同的数字放在一起
【发布时间】:2019-03-20 21:18:32
【问题描述】:
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


【解决方案1】:

您可以使用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]

【讨论】:

    【解决方案2】:

    也许只是对列表进行排序:

    lst = sorted(lst)

    【讨论】:

      【解决方案3】:
      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()
      

      【讨论】:

        【解决方案4】:

        首先让我们创建另一个列表来保持唯一编号的顺序(如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 可以大大简化此代码。

        【讨论】:

        • 关于如何将括号括在打印语句中重复的值周围的任何线索?
        • 前。 1 2 5 (4 4 4) 3 2 (6 6) 2 (1 1)
        • 做一个for n in unsorted_setprint("({})".format(' '.join([n for _ in range(lst.count(n))])), end=' ')
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-08-23
        • 2012-04-29
        • 1970-01-01
        • 2020-11-10
        • 2021-06-25
        • 2018-08-10
        • 1970-01-01
        相关资源
        最近更新 更多