首页 文章

洗牌对象列表

提问于
浏览
578

我在Python中有一个对象列表,我想要将它们洗牌 . 我以为我可以使用 random.shuffle 方法,但是当列表是对象时,这似乎失败了 . 是否有一种方法可以改变对象或其他方式?

import random

class a:
    foo = "bar"

a1 = a()
a2 = a()
b = [a1,a2]

print random.shuffle(b)

这将失败 .

23 回答

  • 0

    你可以构建一个函数,它将列表作为参数并返回列表的混乱版本:

    from random import *
    
    def listshuffler(inputlist):
        for i in range(len(inputlist)):
            swap = randint(0,len(inputlist)-1)
            temp = inputlist[swap]
            inputlist[swap] = inputlist[i]
            inputlist[i] = temp
        return inputlist
    
  • 0

    当使用'foo'调用时,'print func(foo)'将打印'func'的返回值 . 'shuffle'但是返回类型为None,因为列表将被修改到位,因此它不会打印任何内容 . 解决方法:

    # shuffle the list in place 
    random.shuffle(b)
    
    # print it
    print(b)
    

    如果您更喜欢函数式编程风格,您可能需要创建以下包装函数:

    def myshuffle(ls):
        random.shuffle(ls)
        return ls
    
  • 0
    #!/usr/bin/python3
    
    import random
    
    s=list(range(5))
    random.shuffle(s) # << shuffle before print or assignment
    print(s)
    
    # print: [2, 4, 1, 3, 0]
    
  • 22

    你可以这样做:

    >>> A = ['r','a','n','d','o','m']
    >>> B = [1,2,3,4,5,6]
    >>> import random
    >>> random.sample(A+B, len(A+B))
    [3, 'r', 4, 'n', 6, 5, 'm', 2, 1, 'a', 'o', 'd']
    

    如果要返回两个列表,则将此长列表拆分为两个 .

  • -2
    import random
    
    class a:
        foo = "bar"
    
    a1 = a()
    a2 = a()
    a3 = a()
    a4 = a()
    b = [a1,a2,a3,a4]
    
    random.shuffle(b)
    print(b)
    

    shuffle 已就位,所以不要打印结果,这是 None ,而是列表 .

  • 5

    如果您恰好使用numpy(非常受科学和金融应用程序欢迎),您可以节省自己的导入 .

    import numpy as np    
    np.random.shuffle(b)
    print(b)
    

    http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.shuffle.html

  • 969

    random.shuffle应该工作 . 这是一个示例,其中对象是列表:

    from random import shuffle
    x = [[i] for i in range(10)]
    shuffle(x)
    
    # print x  gives  [[9], [2], [7], [0], [4], [5], [3], [1], [8], [6]]
    # of course your results will vary
    

    请注意,shuffle有效 in place ,并返回None .

  • 5
    def shuffle(_list):
        if not _list == []:
            import random
            list2 = []
            while _list != []:
                card = random.choice(_list)
                _list.remove(card)
                list2.append(card)
            while list2 != []:
                card1 = list2[0]
                list2.remove(card1)
                _list.append(card1)
            return _list
    
  • 0

    当你了解到就地改组就是问题所在 . 我也经常遇到问题,而且似乎也经常忘记如何复制列表 . 使用 sample(a, len(a)) 是解决方案,使用 len(a) 作为样本大小 . 有关Python文档,请参阅https://docs.python.org/3.6/library/random.html#random.sample .

    这是一个使用 random.sample() 的简单版本,它将混洗后的结果作为新列表返回 .

    import random
    
    a = range(5)
    b = random.sample(a, len(a))
    print a, b, "two list same:", a == b
    # print: [0, 1, 2, 3, 4] [2, 1, 3, 4, 0] two list same: False
    
    # The function sample allows no duplicates.
    # Result can be smaller but not larger than the input.
    a = range(555)
    b = random.sample(a, len(a))
    print "no duplicates:", a == list(set(b))
    
    try:
        random.sample(a, len(a) + 1)
    except ValueError as e:
        print "Nope!", e
    
    # print: no duplicates: True
    # print: Nope! sample larger than population
    
  • 20

    我也花了一些时间才能做到这一点 . 但是shuffle的文档很清楚:

    shuffle list x到位;返回无 .

    所以你不应该 print random.shuffle(b) . 而是 random.shuffle(b) 然后 print b .

  • 94
    import random
    class a:
        foo = "bar"
    
    a1 = a()
    a2 = a()
    b = [a1.foo,a2.foo]
    random.shuffle(b)
    
  • 7

    在某些情况下使用numpy数组时,使用 random.shuffle 在数组中创建了重复数据 .

    另一种方法是使用 numpy.random.shuffle . 如果您已经使用numpy,这是通用 random.shuffle 的首选方法 .

    numpy.random.shuffle

    Example

    >>> import numpy as np
    >>> import random
    

    使用 random.shuffle

    >>> foo = np.array([[1,2,3],[4,5,6],[7,8,9]])
    >>> foo
    
    array([[1, 2, 3],
           [4, 5, 6],
           [7, 8, 9]])
    
    
    >>> random.shuffle(foo)
    >>> foo
    
    array([[1, 2, 3],
           [1, 2, 3],
           [4, 5, 6]])
    

    使用 numpy.random.shuffle

    >>> foo = np.array([[1,2,3],[4,5,6],[7,8,9]])
    >>> foo
    
    array([[1, 2, 3],
           [4, 5, 6],
           [7, 8, 9]])
    
    
    >>> np.random.shuffle(foo)
    >>> foo
    
    array([[1, 2, 3],
           [7, 8, 9],
           [4, 5, 6]])
    
  • -1

    如果您有多个列表,则可能需要先定义排列(将列表重新排列/重新排列列表中的项目的方式),然后将其应用于所有列表:

    import random
    
    perm = list(range(len(list_one)))
    random.shuffle(perm)
    list_one = [list_one[index] for index in perm]
    list_two = [list_two[index] for index in perm]
    

    Numpy / Scipy

    如果您的列表是numpy数组,则更简单:

    import numpy as np
    
    perm = np.random.permutation(len(list_one))
    list_one = list_one[perm]
    list_two = list_two[perm]
    

    mpu

    我创建了小实用程序包mpu,它具有consistent_shuffle函数:

    import mpu
    
    # Necessary if you want consistent results
    import random
    random.seed(8)
    
    # Define example lists
    list_one = [1,2,3]
    list_two = ['a', 'b', 'c']
    
    # Call the function
    list_one, list_two = mpu.consistent_shuffle(list_one, list_two)
    

    请注意 mpu.consistent_shuffle 采用任意数量的参数 . 因此,您也可以随机播放三个或更多列表 .

  • 2
    from random import random
    my_list = range(10)
    shuffled_list = sorted(my_list, key=lambda x: random())
    

    对于您想要交换排序功能的某些应用程序,此替代方法可能很有用 .

  • 32

    确保你没有命名你的源文件random.py,并且你的工作目录中没有一个名为random.pyc的文件..要么你的程序可能会尝试导入你的本地random.py文件而不是pythons随机模块 .

  • 0

    它工作正常 . 我在这里尝试使用函数作为列表对象:

    from random import shuffle
    
        def foo1():
            print "foo1",
    
        def foo2():
            print "foo2",
    
        def foo3():
            print "foo3",
    
        A=[foo1,foo2,foo3]
    
        for x in A:
            x()
    
        print "\r"
    
        shuffle(A)
        for y in A:
            y()
    

    打印出:foo1 foo2 foo3 foo2 foo3 foo1(最后一行中的foos有一个随机顺序)

  • 9
    >>> import random
    >>> a = ['hi','world','cat','dog']
    >>> random.shuffle(a,random.random)
    >>> a
    ['hi', 'cat', 'dog', 'world']
    

    这对我来说可以 . 确保设置随机方法 .

  • 2

    可以定义一个名为 shuffled 的函数(与 sort vs sorted 相同)

    def shuffled(x):
        import random
        y = x[:]
        random.shuffle(y)
        return y
    
    x = shuffled([1, 2, 3, 4])
    print x
    
  • -1

    计划:写出洗牌而不依赖于库来进行繁重的工作 . 示例:从元素0开始,从头开始查看列表;为它找到一个新的随机位置,比如说6,将0的值放在6中,将6的值放在0中 . 转到元素1并重复此过程,依此类推到列表的其余部分

    import random
    iteration = random.randint(2, 100)
    temp_var = 0
    while iteration > 0:
    
        for i in range(1, len(my_list)): # have to use range with len()
            for j in range(1, len(my_list) - i):
                # Using temp_var as my place holder so I don't lose values
                temp_var = my_list[i]
                my_list[i] = my_list[j]
                my_list[j] = temp_var
    
            iteration -= 1
    
  • 1

    你可以使用shuffle或者样品 . 两者都来自随机模块 .

    import random
    def shuffle(arr1):
        n=len(arr1)
        b=random.sample(arr1,n)
        return b
    

    要么

    import random
    def shuffle(arr1):
        random.shuffle(arr1)
        return arr1
    
  • 0
    """ to shuffle random, set random= True """
    
    def shuffle(x,random=False):
         shuffled = []
         ma = x
         if random == True:
             rando = [ma[i] for i in np.random.randint(0,len(ma),len(ma))]
             return rando
         if random == False:
              for i in range(len(ma)):
              ave = len(ma)//3
              if i < ave:
                 shuffled.append(ma[i+ave])
              else:
                 shuffled.append(ma[i-ave])    
         return shuffled
    
  • 0

    The shuffling process is "with replacement" ,所以每个项目的发生可能会改变!至少当列表中的项目也列出时 .

    例如 . ,

    ml = [[0], [1]] * 10
    

    后,

    random.shuffle(ml)
    

    [0]的数量可以是9或8,但不是10 .

  • 37

    对于单行,请使用 random.sample(list_to_be_shuffled, length_of_the_list) 作为示例:

    import random
    random.sample(list(range(10)), 10)
    

    输出:[2,9,7,8,3,0,4,1,6,5]

相关问题