如何使用python洗牌列表中的项?

2024-06-16 10:17:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在不需要导入任何模块的情况下,对列表中的项进行快速随机排列。 所以一个函数应该返回一个riffle shuffle列表,riffle shuffle首先将它分成两个列表,然后将它们交叉放入一个列表中。在

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

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


Tags: 模块函数列表情况交叉shuffleriffle
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版

^{pr2}$

如果您不喜欢导入,简单的LCG很容易编写代码:

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

lcg.val = id('') # seed

然后:

^{pr2}$

这很有趣!禁止进口!在

问题是,我们需要一个硬币抛硬币,而不需要进口任何东西。听起来像是对<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)

给出:

^{pr2}$

相关问题 更多 >