繁体   English   中英

在没有 random.shuffle() python 的情况下随机化元组列表

[英]Randomizing a list of tuples without random.shuffle() python

我有一个元组列表,看起来像... deck=[(1,'clubs'),(1,'hearts') ...依此类推到(13,'diamonds')

我如何将此列表随机化为类似...

[(5,'spades'),(12,'clubs'),(3,'clubs') ,...等等?

我试过使用random.randint() ,但似乎没有任何效果。 而且我不能使用 random.shuffle()

你想要random.shuffle()

>>> import random
>>> l = [1, 2, 3, 4, 5]
>>> random.shuffle(l)
>>> l
[2, 1, 5, 3, 4]

由于您似乎不能使用random.shuffle ,也许您的老师希望您使用random.randint()来获得 1-13 之间的随机数,然后是随机花色(红心、梅花、钻石、黑桃)和形式这样的清单。 请记住,您需要检查该卡是否已存在于列表中。

尝试先尝试,但如果您不能这样做,那么这里是解决方案。 我强烈建议您先使用我上面提到的方法。

l = []
while len(l) < 52:
    number = random.randint(1, 13)
    suit = random.choice(['hearts', 'clubs', 'diamonds', 'spades'])
    card = (number, suit)
    if card not in l:
        l.append(card)

如果你想对预先存在的列表进行混洗,而不是创建已经混洗过的列表,那么做与random.shuffle可能所做的非常相似的工作并不难(我故意避免检查源代码以避免在这里有罪知识):

deck = [(1,'clubs'),(1,'hearts')...]
for i, card in enumerate(deck):
    swapi = random.randrange(i, len(deck))
    deck[i], deck[swapi] = deck[swapi], card

所做的一切就是将牌组中的每张牌与一张牌或它后面的牌交换,通过对每张牌这样做,最终结果不会保持原始牌组的任何顺序。

   import time
   test_list = [r for r in range(20)]
   print("The original list is : " + str(test_list))
   for i in range(len(test_list)):
    n=str(time.time())[-1]
    j=int(n)

    # Swap arr[i] with the element at random index
    if j < len(test_list):
     test_list[i], test_list[j] = test_list[j], test_list[i]

   print("The shuffled list is : " + str(test_list))

暂无
暂无

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

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