打印lis的名称

2024-06-01 00:29:27 发布

您现在位置:Python中文网/ 问答频道 /正文

import random
Diamonds = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, "Jack", "Queen", "King"]
Hearts = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, "Jack", "Queen", "King"]
Clubs = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, "Jack", "Queen", "King"]
Spades = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, "Jack", "Queen", "King"]
suitvalues = [Diamonds, Hearts, Clubs, Spades]
potentialsuit = random.choice(suitvalues)
potentialcard = random.choice(potentialsuit)
print(potentialcard ,"of" ,potentialsuit.title)

我的问题是潜在诉讼标题part打印整个列表,而我只想打印列表名称。我知道我写的部分解决不了问题,但那只是一个替代品。你知道吗


Tags: import列表randomprintjackchoicequeendiamonds
3条回答

这是行不通的,因为列表(和其他Python对象一样)没有名称。你知道吗

想象一下下面的场景:

x = [1, 2, 3]
y = x

y,它不仅是x的副本,而且引用相同的列表(您可以通过询问x is y看到这一点),它对于列表的名称与x一样有效。那么....title应该选择哪个名字呢?你知道吗


解决问题的许多方法之一是将卡片存储在字典中:

import random

suits = {
    "Diamonds": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, "Jack", "Queen", "King"], 
    "Hearts": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, "Jack", "Queen", "King"], 
    "Clubs": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, "Jack", "Queen", "King"], 
    "Spades": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, "Jack", "Queen", "King"],
}

potentialsuit = random.choice(list(suits))
potentialcard = random.choice(suits[potentialsuit])
print(potentialcard, "of", potentialsuit)

list(suits)利用了这样一个事实:对字典进行迭代会产生它的键(suits)。potentialsuit将不再是卡片值的列表,而是西装的名称,例如“俱乐部”。然后,第二个选项选择suits["Clubs"]中的一个,即卡值列表。你知道吗

想想看,像这样随机选择一张牌是没有意义的;你不需要四份名单。相反,以下内容就足够了:

import random
suit = random.choice(["Diamonds", "Hearts", "Clubs", "Spades"])
value = random.choice([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, "Jack", "Queen", "King"])
print(value, "of", suit)

这将为您解决:

import random

face_card = ['King', 'Queen', 'Jack']
suit_card = ['Diamonds', 'Clubs', 'Spades', 'Hearts']
for x in range(1):
    choice = random.randint(1, 10)
    face_card.append(choice)  # Inserts integer randomly in to list
ran_fcard = random.choice(face_card)
ran_scard = random.choice(suit_card)

print('The card chosen is {} of {}'.format(ran_fcard, ran_scard))
face_card = ['King', 'Queen', 'Jack'] # Resets list to face cards

每次的输出都会不同,您可以在那里得到整数,而不需要长时间的分割选择代码。你知道吗

这是我得到的前3个输出:

The card chosen is 6 of Spades
The card chosen is King of Diamonds
The card chosen is 10 of Spades

我不知道如何打印变量名,但我有两个想法可以帮助您:

  1. 你也许可以在这个other discussion中找到帮助。你知道吗
  2. 我的建议是——如果你的案例和你写的例子相似的话——使用字典,和L3viathansaid一样。你知道吗

相关问题 更多 >