如何将随机键值对传递给 Python 中的 function/constructor?
How to pass a random key-value-pair to a function/constructor in Python?
我有这个词典
cards = {
'A': 1,
'2': 2,
'3': 3,
'4': 4,
'5': 5,
'6': 6,
'7': 7,
'8': 8,
'9': 9,
'10': 10,
'J': 10,
'Q': 10,
'K': 10
}
还有这个class
class Dealer:
def __init__(self, hand1, hand2):
self.hand1 = hand1
self.hand2 = hand2
并且我想将一个随机键值对传递给构造函数。
我不知道怎么...
我试过这个
dealer = Dealer(cards, cards)
但它会通过整个字典。
我也试过这个
dealer = Dealer(cards[random.choice(list(cards.keys()))], cards[random.choice(list(cards.keys()))])
并且可以获得一个随机值,但我想要一个键值对,或者至少只是传递它们的键?
你走在正确的轨道上。从你的字典中获取一个键,然后用它来查找它对应的值。像这样:
import random
adict = {"1":"4","2":"5"}
k = random.choice(list(adict.keys()))
pair = (k, adict[k])
print(pair)
# output: ('1','4')
我有这个词典
cards = {
'A': 1,
'2': 2,
'3': 3,
'4': 4,
'5': 5,
'6': 6,
'7': 7,
'8': 8,
'9': 9,
'10': 10,
'J': 10,
'Q': 10,
'K': 10
}
还有这个class
class Dealer:
def __init__(self, hand1, hand2):
self.hand1 = hand1
self.hand2 = hand2
并且我想将一个随机键值对传递给构造函数。 我不知道怎么... 我试过这个
dealer = Dealer(cards, cards)
但它会通过整个字典。
我也试过这个
dealer = Dealer(cards[random.choice(list(cards.keys()))], cards[random.choice(list(cards.keys()))])
并且可以获得一个随机值,但我想要一个键值对,或者至少只是传递它们的键?
你走在正确的轨道上。从你的字典中获取一个键,然后用它来查找它对应的值。像这样:
import random
adict = {"1":"4","2":"5"}
k = random.choice(list(adict.keys()))
pair = (k, adict[k])
print(pair)
# output: ('1','4')