将字典中的一个值附加到列表中

时间:2013-12-27 20:32:27

标签: python list dictionary

目前我正在研究一个包含大量字典的程序,其中包含普通卡片中的所有卡片。

我想要做的是将每张卡都附加到列表中。我将使用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个钻石,我想要附加第二个值,即“钻石的六个”到列表中。

我该怎么做?

2 个答案:

答案 0 :(得分: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))

答案 1 :(得分:0)

尝试将其附加到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字典,这部分

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

生成随机数以获取随机卡。您可能希望将范围(1,x)修改为所需的数字。

修改

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