[英]how to shuffle items of a list using python?
我想在不需要導入任何模塊的情況下對列表中的項目進行排序。 因此,一個函數應該返回一個淺灘混洗列表,淺灘混洗是首先將其分成兩個列表,然后將它們交織到一個列表中的地方。
例如list = [a,b,c,d]
淺灘改組后應為[c,a,d,b]或[a,c,b,d]
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
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.