简体   繁体   English

假设我在Python中有一个列表。 按部分将其随机化的最有效的Python方法是什么?

[英]Suppose I had a list in Python. What's the most pythonic and efficient way to randomize it by sections?

I have a list of X items. 我有X件物品的清单。 I want the first 10 to be randomized. 我希望将前10个随机化。 Then, the 2nd 10 items to be randomized. 然后,将第二个10个项目随机化。 Then the 3rd. 然后是第三名。

What's the most efficient way to do this? 最有效的方法是什么?

It's good to break apart problems into smaller problems which can be solved with reusable parts. 将问题分解为较小的问题,用可重用的零件可以解决,这是很好的。 The grouper idiom provides one such reusable part: it takes an iterable and groups its elements into groups of size n: 石斑鱼成语提供了这样一个可重用的部分:它需要一个可迭代并将其元素分组为大小为n的组:

import random
import itertools

def grouper(n, iterable, fillvalue=None):
    # Source: http://docs.python.org/library/itertools.html#recipes
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    return itertools.izip_longest(*[iter(iterable)]*n,fillvalue=fillvalue)

X=100
alist=xrange(X)
blist=[]
for group in grouper(10,alist):
    group=list(group)
    random.shuffle(group)
    blist.extend(group)
    print(group)

# [7, 6, 4, 9, 8, 1, 5, 2, 0, 3]
# [16, 19, 11, 15, 12, 18, 10, 17, 13, 14]
# [26, 27, 28, 22, 24, 21, 23, 20, 25, 29]
# [33, 32, 37, 39, 38, 35, 30, 36, 34, 31]
# [49, 46, 47, 42, 40, 48, 44, 43, 41, 45]
# [55, 51, 50, 52, 56, 58, 57, 53, 59, 54]
# [69, 66, 61, 60, 64, 68, 62, 67, 63, 65]
# [73, 76, 71, 78, 72, 77, 70, 74, 79, 75]
# [85, 88, 82, 87, 80, 83, 84, 81, 89, 86]
# [92, 90, 95, 98, 94, 97, 91, 93, 99, 96]  

print(blist)
# [7, 6, 4, 9, 8, 1, 5, 2, 0, 3, 16, 19, 11, 15, 12, 18, 10, 17, 13, 14, 26, 27, 28, 22, 24, 21, 23, 20, 25, 29, 33, 32, 37, 39, 38, 35, 30, 36, 34, 31, 49, 46, 47, 42, 40, 48, 44, 43, 41, 45, 55, 51, 50, 52, 56, 58, 57, 53, 59, 54, 69, 66, 61, 60, 64, 68, 62, 67, 63, 65, 73, 76, 71, 78, 72, 77, 70, 74, 79, 75, 85, 88, 82, 87, 80, 83, 84, 81, 89, 86, 92, 90, 95, 98, 94, 97, 91, 93, 99, 96]

How about this? 这个怎么样?

import random

a = [1,2,3,4,5,6,7,8,9,0,'a','b','c','d','e','f','g','h','i','j','k','l','m']
parts=[a[i:i+10] for i in range(0, len(a), 10)]
map(random.shuffle,parts)
result = sum(parts,[])
import random

random.seed()
a = [1,2,3,4,5,6,7,8,9,0,'a','b','c','d','e','f','g','h','i','j']

def groupRand (elems, gsize=10):
    temp_list = elems[:]
    result = []
    while temp_list:
        aux = temp_list[:gsize]
        random.shuffle (aux)
        result += aux
        del(temp_list[:gsize])
    return result

print (groupRand(a))

# [7, 8, 3, 1, 0, 6, 9, 4, 2, 5, 'i', 'e', 'g', 'b', 'h', 'c', 'j', 'd', 'f', 'a']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM