在没有 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
所要做的就是将牌组中的每张牌与其前面或后面的牌交换,并且通过对每张牌这样做,最终结果保持原始牌组顺序的none。
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))
我有一个元组列表,看起来像...
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
所要做的就是将牌组中的每张牌与其前面或后面的牌交换,并且通过对每张牌这样做,最终结果保持原始牌组顺序的none。
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))