gpt4 book ai didi

python - 排列具有混合元素的列表列表(np.random.permutation() 因 ValueError 而失败)

转载 作者:行者123 更新时间:2023-11-28 21:45:27 25 4
gpt4 key购买 nike

我正在尝试置换一个由具有混合类型元素的子列表组成的列表:

import numpy as np

a0 = ['122', 877.503017, 955.471176, [21.701201, 1.315585]]
a1 = ['176', 1134.076908, 1125.504758, [19.436181, 0.9987899]]
a2 = ['177', 1038.686843, 1018.987868, [19.539959, 1.183997]]
a3 = ['178', 878.999081, 1022.050447, [19.6448771, 1.1867719]]

a = [a0, a1, a2, a3]

b = np.random.permutation(a)

这将失败:

ValueError: cannot set an array element with a sequence

是否有内置函数可以生成这样的排列?

我需要生成一个随机排列,我并不是要获得所有可能的排列。


我检查了给出的三个答案:

import time
import random

# np.random.permutation()
start = time.time()
for _ in np.arange(100000):
b = np.random.permutation([np.array(i, dtype='object') for i in a])
print(time.time() - start)

# np.random.shuffle()
start = time.time()
for _ in np.arange(100000):
b = a[:]
np.random.shuffle(b)
print(time.time() - start)

# random.shuffle()
start = time.time()
for _ in np.arange(100000):
random.shuffle(a)
print(time.time() - start)

结果是:

1.47580695152
0.11471414566
0.26300907135

所以 np.random.shuffle() 解决方案比 np.random.permutation() 快 10 倍,比 random.shuffle( )

最佳答案

使用 np.random.shuffle 怎么样? ?

# if you want the result in another list, otherwise just apply shuffle to a
b = a[:]
# shuffle the elements
np.random.shuffle(b)
# see the result of the shuffling
print(b)

参见 this answer shufflepermutation

的区别

关于python - 排列具有混合元素的列表列表(np.random.permutation() 因 ValueError 而失败),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39398877/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com