检索字典值Python

2024-04-27 03:56:09 发布

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

我目前有一个相当大的字典程序。你知道吗

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",

     5.1:"Five of Spades",
     5.2:"Five of Clubs",
     5.3:"Five of Diamonds",
     5.4:"Five of Hearts",

     6.1:"Six of Spades",
     6.2:"Six of Clubs",
     6.3:"Six of Diamonds",
     6.4:"Six of Hearts",

     7.1:"Seven of Spades",
     7.2:"Seven of Clubs",
     7.3:"Seven of Diamonds",
     7.4:"Seven of Hearts",

     8.1:"Eight of Spades",
     8.2:"Eight of Clubs",
     8.3:"Eight of Diamonds",
     8.4:"Eight of Hearts",

     9.1:"Nine of Spades",
     9.2:"Nine of Clubs",
     9.3:"Nine of Diamonds",
     9.4:"Nine of Hearts",

     10.1:"Ten of Spades",
     10.2:"Ten of Clubs",
     10.3:"Ten of Diamonds",
     10.4:"Ten of Hearts",

     11.1:"Jack of Spades",
     11.2:"Jack of Clubs",
     11.3:"Jack of Diamonds",
     11.4:"Jack of Hearts",

     12.1:"Queen of Spades",
     12.2:"Queen of Clubs",
     12.3:"Queen of Diamonds",
     12.4:"Queen of Diamonds",

     13.1:"King of Spades",
     13.2:"King of Clubs",
     13.3:"King of Diamonds",
     13.4:"King of Hearts"}

我想做的事。例如,打印11.2(球杆千斤顶)的相应值。然后我还想打印出相应的俱乐部杰克值(11.2)。你知道吗

我该怎么做?你知道吗

编辑

当然,我想补充的是,它不会每次都是相同的值。它将被改变。程序生成一个介于1和13之间的随机数,然后再生成一个介于1和4之间的随机数,然后将这两个随机数加在一起,这样它就是#。#然后我想检索该浮点对应的值。你知道吗


Tags: ofthreefouracefivetwosixseven
1条回答
网友
1楼 · 发布于 2024-04-27 03:56:09

为随机选择的数字打印相应的值将很容易:

print cards[randomNumber]

当您要进行反向查找,并打印出与“Jack of Clubs”相对应的值或相应的卡名时,就会出现问题。对于传统词典,这将需要很长时间,因为它需要搜索词典中的每个值。你知道吗

为了避免这种情况,您可以创建两个字典。不过,使用davidzwicker链接到的Two way/reverse map问题中的一个建议会更有效。你知道吗

相关问题 更多 >