繁体   English   中英

如何使用python随机播放列表项?

[英]how to shuffle items of a list using python?

我想在不需要导入任何模块的情况下对列表中的项目进行排序。 因此,一个函数应该返回一个浅滩混洗列表,浅滩混洗是首先将其分成两个列表,然后将它们交织到一个列表中的地方。

例如list = [a,b,c,d]

浅滩改组后应为[c,a,d,b]或[a,c,b,d]

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)

这好有趣! 没有进口!

问题是我们需要不输入任何东西的硬币翻转。 听起来像是对<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']

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

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

lcg.val = id('') # seed

接着:

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

暂无
暂无

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

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