开发者

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

开发者 https://www.devze.com 2023-01-08 09:59 出处:网络
I have a list 开发者_开发问答of X items. I want the first 10 to be randomized. Then, the 2nd 10 items to be randomized. Then the 3rd.

I have a list 开发者_开发问答of X items. I want the first 10 to be randomized. Then, the 2nd 10 items to be randomized. Then the 3rd.

What's the most efficient way to do this?


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


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:

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]


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

精彩评论

暂无评论...
验证码 换一张
取 消