如何使用python来混淆列表中的项目?

时间:2013-11-19 09:37:56

标签: python list

我想在不必导入任何模块的情况下重复列表中的随机项目。 所以一个函数应该返回一个riffle shuffled列表,riffle shuffle是首先将它分成两个列表然后将它们交织到一个列表中的地方。

例如,

列表= [a,b,c,d]

应该是 riffle洗牌之后[c,a,d,b]或[a,c,b,d]

3 个答案:

答案 0 :(得分:3)

Python2版本

cards = range(52)
a = cards[:len(cards)/2]
b = cards[len(cards)/2:]
if id('')/0xffff&1:
    a, b = b, a
cards[::2] = a
cards[1::2] = b
print cards

Python3版本

cards = list(range(52))
a = cards[:len(cards)//2]
b = cards[len(cards)//2:]
if id('')//0xffff&1:
    a, b = b, a
cards[::2] = a
cards[1::2] = b
print(cards)

答案 1 :(得分:1)

这很有趣!没有进口!

问题是我们需要硬币翻转而不需要输入任何东西。听起来像<some random int> % 2 == 0的测试。困难的部分是<some random int>。堆上的指针可能?

input_list = ['a', 'b', 'c', 'd']

#you should empty this once and awhile
fill_my_heap = [] 

#nothing to see here
class Dummy(): 
    pass

for x in range(0,10):    
    #give me a new pointer
    foo = Dummy()
    #prevent reuse of heap memory location
    fill_my_heap.append(foo) 
    #get id of new class and strip its last digit because that was always even
    ptr_int = int(str(id(foo))[:-1]) 
    #test to see if this is even. Should be 50% of the time. Sort of... ;)
    is_even = ptr_int%2==0 
    #split list
    a = input_list[:len(input_list)/2]
    b = input_list[len(input_list)/2:]
    #and assemble output based on even-switch
    if is_even:
        output = a + b
    else:
        output = b + a
    print(output)

给出:

['a', 'b', 'c', 'd']
['a', 'b', 'c', 'd']
['a', 'b', 'c', 'd']
['c', 'd', 'a', 'b']
['a', 'b', 'c', 'd']
['a', 'b', 'c', 'd']
['c', 'd', 'a', 'b']
['a', 'b', 'c', 'd']
['c', 'd', 'a', 'b']
['a', 'b', 'c', 'd']

答案 2 :(得分:0)

如果您不喜欢导入,那么简单的LCG代码非常简单:

def lcg(_):
    lcg.val = (1664525 * lcg.val + 1013904223) & 0xffffffff
    return lcg.val

lcg.val = id('') # seed

然后:

print sorted(range(52), key=lcg)