打乱对象列表

发布于 2024-07-23 04:56:21 字数 277 浏览 10 评论 0原文

如何打乱对象列表? 我尝试了 random.shuffle

import random

b = [object(), object()]

print(random.shuffle(b))

但是它输出:

None

How do I shuffle a list of objects? I tried random.shuffle:

import random

b = [object(), object()]

print(random.shuffle(b))

But it outputs:

None

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(26

春风十里 2024-07-30 04:56:21

random.shuffle 应该可以工作。 下面是一个示例,其中对象是列表:

from random import shuffle

x = [[i] for i in range(10)]
shuffle(x)
print(x)

# print(x)  gives  [[9], [2], [7], [0], [4], [5], [3], [1], [8], [6]]

请注意,shuffle就地工作,并返回None

更一般地,在 Python 中,可变对象可以传递到函数中,当函数改变这些对象时,标准是返回 None (而不是,比如说,改变的对象)。

random.shuffle should work. Here's an example, where the objects are lists:

from random import shuffle

x = [[i] for i in range(10)]
shuffle(x)
print(x)

# print(x)  gives  [[9], [2], [7], [0], [4], [5], [3], [1], [8], [6]]

Note that shuffle works in place, and returns None.

More generally in Python, mutable objects can be passed into functions, and when a function mutates those objects, the standard is to return None (rather than, say, the mutated object).

毁梦 2024-07-30 04:56:21

正如您所知,就地洗牌是问题所在。 我也经常遇到问题,似乎也经常忘记如何复制列表。 使用 sample(a, len(a)) 是解决方案,使用 len(a) 作为样本大小。 请参阅 https://docs.python.org/3.6/library/random。 html#random.sample 获取 Python 文档。

这是一个使用 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

As you learned the in-place shuffling was the problem. I also have problem frequently, and often seem to forget how to copy a list, too. Using sample(a, len(a)) is the solution, using len(a) as the sample size. See https://docs.python.org/3.6/library/random.html#random.sample for the Python documentation.

Here's a simple version using random.sample() that returns the shuffled result as a new list.

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
青衫负雪 2024-07-30 04:56:21

random.shuffle 的文档指出它会

将序列x打乱就位

不做:

print(random.shuffle(xs))  # WRONG!

相反,做:

random.shuffle(xs)
print(xs)

The documentation for random.shuffle states that it will

Shuffle the sequence x in place.

Don't do:

print(random.shuffle(xs))  # WRONG!

Instead, do:

random.shuffle(xs)
print(xs)
污味仙女 2024-07-30 04:56:21
#!/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]
#!/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]
耶耶耶 2024-07-30 04:56:21

对于 numpy (科学和金融应用程序的流行库),请使用 np.random.shuffle

import numpy as np
b = np.arange(10)
np.random.shuffle(b)
print(b)

For numpy (popular library for scientific and financial applications), use np.random.shuffle:

import numpy as np
b = np.arange(10)
np.random.shuffle(b)
print(b)
被你宠の有点坏 2024-07-30 04:56:21
>>> import random
>>> a = ['hi','world','cat','dog']
>>> random.shuffle(a,random.random)
>>> a
['hi', 'cat', 'dog', 'world']

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

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

It works fine for me. Make sure to set the random method.

—━☆沉默づ 2024-07-30 04:56:21

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

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 ,它具有 consistency_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.consistency_shuffle 接受任意数量的参数。 因此,您还可以用它来洗牌三个或更多列表。

If you have multiple lists, you might want to define the permutation (the way you shuffle the list / rearrange the items in the list) first and then apply it to all lists:

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

If your lists are numpy arrays, it is simpler:

import numpy as np

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

mpu

I've created the small utility package mpu which has the consistent_shuffle function:

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)

Note that mpu.consistent_shuffle takes an arbitrary number of arguments. So you can also shuffle three or more lists with it.

巴黎盛开的樱花 2024-07-30 04:56:21

对于单行,请使用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]

For one-liners, userandom.sample(list_to_be_shuffled, length_of_the_list) with an example:

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

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

梦回梦里 2024-07-30 04:56:21
from random import random
my_list = range(10)
shuffled_list = sorted(my_list, key=lambda x: random())

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

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

This alternative may be useful for some applications where you want to swap the ordering function.

花想c 2024-07-30 04:56:21

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

另一种方法是使用 numpy.random.shuffle。 如果您已经在使用 numpy,那么这是优于通用 random.shuffle 的首选方法。

numpy.random.shuffle

示例

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

In some cases when using numpy arrays, using random.shuffle created duplicate data in the array.

An alternative is to use numpy.random.shuffle. If you're working with numpy already, this is the preferred method over the generic random.shuffle.

numpy.random.shuffle

Example

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

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

Using 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]])
弥枳 2024-07-30 04:56:21

当用“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

'print func(foo)' will print the return value of 'func' when called with 'foo'.
'shuffle' however has None as its return type, as the list will be modified in place, hence it prints nothing.
Workaround:

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

# print it
print(b)

If you're more into functional programming style you might want to make the following wrapper function:

def myshuffle(ls):
    random.shuffle(ls)
    return ls
意犹 2024-07-30 04:56:21

我们可以定义一个名为 shuffled 的函数(与 sortsorted 的含义相同)

def shuffled(x):
    import random
    y = x[:]
    random.shuffle(y)
    return y

x = shuffled([1, 2, 3, 4])
print x

One can define a function called shuffled (in the same sense of sort vs sorted)

def shuffled(x):
    import random
    y = x[:]
    random.shuffle(y)
    return y

x = shuffled([1, 2, 3, 4])
print x
明月松间行 2024-07-30 04:56:21
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,而是打印列表。

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 is in place, so do not print result, which is None, but the list.

甜嗑 2024-07-30 04:56:21

您可以使用 shuffle 或 Sample 。 两者都来自 random 模块。

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

you can either use shuffle or sample . both of which come from random module.

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

OR

import random
def shuffle(arr1):
    random.shuffle(arr1)
    return arr1
清秋悲枫 2024-07-30 04:56:21

如果您需要就地改组和操作种子的能力,此代码段将有所帮助:

from random import randint

a = ['hi','world','cat','dog']
print(sorted(a, key=lambda _: randint(0, 1)))

请记住,“改组”是按随机键进行排序。

In case you need an in-place shuffling and ability to manipulate seed, this snippet would help:

from random import randint

a = ['hi','world','cat','dog']
print(sorted(a, key=lambda _: randint(0, 1)))

Remember that "shuffling" is a sorting by randomised key.

小…红帽 2024-07-30 04:56:21

确保您没有将源文件命名为 random.py,并且工作目录中没有名为 random.pyc 的文件。这两种情况都可能导致您的程序尝试导入本地 random.py 文件而不是 python 的 random 模块。

Make sure you are not naming your source file random.py, and that there is not a file in your working directory called random.pyc.. either could cause your program to try and import your local random.py file instead of pythons random module.

灯下孤影 2024-07-30 04:56:21

您可以这样做:

>>> 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']

如果您想返回两个列表,则可以将这个长列表分成两个。

You can go for this:

>>> 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']

if you want to go back to two lists, you then split this long list into two.

往昔成烟 2024-07-30 04:56:21
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
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
猫烠⑼条掵仅有一顆心 2024-07-30 04:56:21

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

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

you could build a function that takes a list as a parameter and returns a shuffled version of the list:

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
明天过后 2024-07-30 04:56:21
""" 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
""" 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
听,心雨的声音 2024-07-30 04:56:21
import random
class a:
    foo = "bar"

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

a1 = a()
a2 = a()
b = [a1.foo,a2.foo]
random.shuffle(b)
南…巷孤猫 2024-07-30 04:56:21

对于任何有兴趣使用索引顺序方法的人 (Ouarda et.al., 1997< /a>) 重新排序列表:

def ISM(dList):
    nList = dList.copy()
    dRng = range(len(dList))
    for i in dRng[:-1]:
        nList[i] = dList[i+1]
    nList[-1] = dList[0]        
    return nList

这适用于单值列表...

valList = [1,2,3,4,5,6,7]

for l in range(len(valList)):
    print(valList)
    dataList = ISM(valList)

这将打印出...

[1, 2, 3, 4, 5, 6, 7]
[2, 3, 4, 5, 6, 7, 1]
[3, 4, 5, 6, 7, 1, 2]
[4, 5, 6, 7, 1, 2, 3]
[5, 6, 7, 1, 2, 3, 4]
[6, 7, 1, 2, 3, 4, 5]
[7, 1, 2, 3, 4, 5, 6]

或嵌套列表的列表...

nestedList = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]

for l in range(len(nestedList)):
    print(nestedList)
    nestedList = ISM(nestedList)

这将打印出...

[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
[[4, 5, 6], [7, 8, 9], [10, 11, 12], [1, 2, 3]]
[[7, 8, 9], [10, 11, 12], [1, 2, 3], [4, 5, 6]]
[[10, 11, 12], [1, 2, 3], [4, 5, 6], [7, 8, 9]]

@Shantanu Sharma 提供了一些很棒的方法,可以将值列表分解为一系列嵌套的值大小为 n 的列表。

这是我使用的方法...

valList = [1,2,3,4,5,6,7,8,9,10,11,12]

# Yield successive n-sized lists from l
def SequenceList(l, n):
    # looping till length l
    for i in range(0, len(l), n):
        yield l[i:i + n]

nestedList = list(SequenceList(valList, 3))

这将打印出来...

[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]

For anyone interested in using the Index Sequential Method (Ouarda et.al., 1997) to reorder a list:

def ISM(dList):
    nList = dList.copy()
    dRng = range(len(dList))
    for i in dRng[:-1]:
        nList[i] = dList[i+1]
    nList[-1] = dList[0]        
    return nList

This will work for a single value list...

valList = [1,2,3,4,5,6,7]

for l in range(len(valList)):
    print(valList)
    dataList = ISM(valList)

This will print out...

[1, 2, 3, 4, 5, 6, 7]
[2, 3, 4, 5, 6, 7, 1]
[3, 4, 5, 6, 7, 1, 2]
[4, 5, 6, 7, 1, 2, 3]
[5, 6, 7, 1, 2, 3, 4]
[6, 7, 1, 2, 3, 4, 5]
[7, 1, 2, 3, 4, 5, 6]

or a list of nested lists...

nestedList = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]

for l in range(len(nestedList)):
    print(nestedList)
    nestedList = ISM(nestedList)

This will print out...

[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
[[4, 5, 6], [7, 8, 9], [10, 11, 12], [1, 2, 3]]
[[7, 8, 9], [10, 11, 12], [1, 2, 3], [4, 5, 6]]
[[10, 11, 12], [1, 2, 3], [4, 5, 6], [7, 8, 9]]

@Shantanu Sharma provides some great methods for breaking a list of values into a sequence of nested lists of size n.

Here's the method I used...

valList = [1,2,3,4,5,6,7,8,9,10,11,12]

# Yield successive n-sized lists from l
def SequenceList(l, n):
    # looping till length l
    for i in range(0, len(l), n):
        yield l[i:i + n]

nestedList = list(SequenceList(valList, 3))

This will print out...

[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
花开雨落又逢春i 2024-07-30 04:56:21

洗牌过程是“有替换”,因此每一项的出现次数都可能发生变化! 至少当列表中的项目也列出时。

例如,

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

之后,

random.shuffle(ml)

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

The shuffling process is "with replacement", so the occurrence of each item may change! At least when when items in your list is also list.

E.g.,

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

After,

random.shuffle(ml)

The number of [0] may be 9 or 8, but not exactly 10.

毁我热情 2024-07-30 04:56:21

计划:写出随机播放,而不依赖库来完成繁重的工作。 示例:从元素 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

Plan: Write out the shuffle without relying on a library to do the heavy lifting. Example: Go through the list from the beginning starting with element 0; find a new random position for it, say 6, put 0’s value in 6 and 6’s value in 0. Move on to element 1 and repeat this process, and so on through the rest of the list

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
固执像三岁 2024-07-30 04:56:21

您可以使用 random.choices() 来随机排列列表。

TEAMS = [A,B,C,D,E,F,G,H]
random.choices(TEAMS,k = len(TEAMS)) 

上面的代码将返回一个与之前的列表长度相同的随机列表。

You can use random.choices() to shuffle your list.

TEAMS = [A,B,C,D,E,F,G,H]
random.choices(TEAMS,k = len(TEAMS)) 

The above code will return a randomized list same length as your previous list.

む无字情书 2024-07-30 04:56:21

效果很好。 我在这里尝试使用函数作为列表对象:

    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
(最后一行的 foo 顺序随机)

It works fine. I am trying it here with functions as list objects:

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

It prints out:
foo1 foo2 foo3
foo2 foo3 foo1
(the foos in the last row have a random order)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文