[英]How can I get 3 lists of unique values from a list of 21 unique values?
I'm doing the basic Python card trick and what I've searched for is too complicated, here's my code: 我正在做基本的Python卡技巧,而我搜索的内容太复杂了,这是我的代码:
import random
import itertools
deck = ["S A","S 2","S 3","S 4","S 5","S 6","S 7","D A","D 2","D 3","D 4","D
5","D 6","D 7","C A","C 2","C 3","C 4","C 5","C 6","C 7"]
random.shuffle(deck)
for z in range(3):
print("Pile ",[z+1])
for i in range(7):
print(deck[i])
What I am trying to do is get it so when I get my 3 piles, I don't want any duplicate values but I can't work out how I do it, or how I get them in 3 separate columns? 我想做的就是得到它,所以当我得到3个桩时,我不希望有任何重复的值,但是我无法弄清楚该如何做或如何在3个单独的列中得到它们?
use 采用
piles=[deck[0::3],deck[1::3],deck[2::3]]
this build 3 lists starting at position 0, 1 and 2 respectively, jumping from item to item with a length of 3. no need to know the size of the initial list. 此版本3的列表分别从位置0、1和2开始,从一个项目跳到另一个长度为3的项目。无需知道初始列表的大小。
Slight modification in your code. 在代码中稍加修改。
n = 0 # starting index of pile 1
for i in range(3):
print("Pile ",[i+1])
for j in range(n,n+7):
print(deck[j])
n = n+7 # update the index to next pile
Try this: 尝试这个:
import random
deck = ["S A","S 2","S 3","S 4","S 5","S 6","S 7","D A","D 2","D 3","D 4","D 5","D 6","D 7","C A","C 2","C 3","C 4","C 5","C 6","C 7"]
data = {}
for i in range(3):
data[i] = []
for j in range(7):
data[i].append(deck.pop(random.randint(0,len(deck)-1)))
print(data)
Randex! Randex! I did not quite get the idea of making 3 columns, as you asked in your question, but this is what you may find useful:
正如您在问题中所问的那样,我不太了解创建3列的想法,但是您可能会发现这很有用:
import random
deck = [
"S A", "S 2", "S 3", "S 4", "S 5", "S 6", "S 7",
"D A", "D 2", "D 3", "D 4", "D 5", "D 6", "D 7",
"C A", "C 2", "C 3", "C 4", "C 5", "C 6", "C 7"
]
hands = {}
for stack in range(3):
hands[stack] = []
You may also assign a randomly generated value to later on .append() and then remove from the list for more code readability 您还可以为稍后在.append()上分配一个随机生成的值,然后将其从列表中删除以提高代码的可读性
for card in range(7):
hands[stack].append(deck.pop(random.randint(0, len(deck) - 1)))
The "hands" will be assigned with a random card from the deck, until every "hand" has 7 cards stacked 从甲板上为“手牌”分配一张随机的牌,直到每只“手牌”堆满7张牌
for stack in hands:
print(stack, '-', hands[stack])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.