将字典中的一个值附加到lis

2024-04-28 10:50:45 发布

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

目前我正在开发一个程序,这个程序有一个大字典,其中包含一副普通卡片中的所有卡片。你知道吗

我要做的是把每一张卡片都附加到一个列表中。我将使用randint()生成一个随机整数来选择卡号。你知道吗

cards = {1.1:"Ace of Spades",
     1.2:"Ace of Clubs", 
     1.3:"Ace of Diamonds", 
     1.4:"Ace of Hearts", 

     2.1:"Two of Spades", 
     2.2:"Two of Clubs", 
     2.3:"Two of Diamonds",
     2.4:"Two of Hearts",

     3.1:"Three of Spades",
     3.2:"Three of Clubs",
     3.3:"Three of Diamonds",
     3.4:"Three of Hearts",

     4.1:"Four of Spades",
     4.2:"Four of Clubs",
     4.3:"Four of Diamonds",
     4.4:"Four of Hearts",

然后另一个来挑选西装。然后我想把所选卡片的值附加到一个列表中。比如说我选了3.2,这是三个俱乐部。我想将该值自动附加到列表中。你知道吗

因此生成一个整数。比如说6,另一个值是随机生成的,比如说3,卡上会有6颗钻石,我想把第二个值,也就是“6颗钻石”加到列表上。你知道吗

我该怎么做?你知道吗


Tags: of程序列表整数threefouracerandint
2条回答

尝试将其附加到list。你知道吗

代码:

import random

cards = {1.1:"Ace of Spades",
     1.2:"Ace of Clubs",
     1.3:"Ace of Diamonds",
     1.4:"Ace of Hearts",
      2.1:"Two of Spades",
     2.2:"Two of Clubs",
     2.3:"Two of Diamonds",
     2.4:"Two of Hearts",

     3.1:"Three of Spades",
     3.2:"Three of Clubs",
     3.3:"Three of Diamonds",
     3.4:"Three of Hearts",

     4.1:"Four of Spades",
     4.2:"Four of Clubs",
     4.3:"Four of Diamonds",
     4.4:"Four of Hearts"}

used_cards = []

def add_card():
    used_cards.append(cards[random.randint(1, 5) + random.randint(1, 5) * 0.1])

add_card()
add_card()

print used_cards

输出:

['Three of Diamonds', 'Three of Spades']

PS: 考虑到我的字典不完整,这一部分

cards[random.randint(1, 5) + random.randint(1, 5) * 0.1

生成随机数以获得随机卡。您可能需要将范围(1,x)修改为所需的数字。你知道吗

编辑:

正如@Peter DeGlopper所说,你可能想改变你在字典中存储卡片的方式。可以使用(1, 1)这样的元组而不是1.1,以避免浮点不准确。你知道吗

# you do not have to write all the names of cards. you can use loop method.
# first create a list of suit and rank names and an empty list for cards.
# then use for loop and append all cards to a list.

suit_names = ['Clubs', 'Diamonds', 'Hearts', 'Spades']
rank_names = ['Ace', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King']
cards=[]
for rank in rank_names:
    for suit in suit_names:
        cards.append(rank+' of '+suit)

print cards

# import random. random has a built in method which chooses elements from list randomly; you can use it instead of ranint.
import random
removed_cards=[]
# create ans empty list for removed cards and append randomly chosen cards to that list.
removed_cards.append(random.choice(cards))

相关问题 更多 >