【发布时间】:2020-02-15 23:26:10
【问题描述】:
我们的目标是玩这个。
我创建了一个字典“all_dice”,并在使用之前将它传递给了 3 个函数。
必须有一种更简单的方法来访问字典,而不必像这样一遍又一遍地传递它。
import random
from random import randint
x = 0
the_dice_chosen = ""
##this is the dictionary
all_dice = {"six":
[["_____",],
["0 0",],
["0 0",],
["0 0",],
["_____",],],
"five":
[["_____",],
["0 0",],
[" 0 ",],
["0 0",],
["_____",],],
"four":
[["_____",],
["0 0",],
[" ",],
["0 0",],
["_____",],],
"three":
[["_____",],
["0 ",],
[" 0 ",],
[" 0",],
["_____",],],
"two":
[["_____",],
["0 ",],
[" ",],
[" 0",],
["_____",],],
"one":
[["_____",],
[" ",],
[" 0 ",],
[" ",],
["_____",],],}
## This prints the dictionary of the numbers chosen side by side.
## Again "all_dice" is passed as "ad" and is used.
def dice_print(ndy,ndz,ad):
x = 0
nday = ad[ndy]
ndaz = ad[ndz]
for i in nday:
print(nday[x], ndaz[x])
x = x + 1
##This creates the random dice numbers.
def dice_roller():
x = randint(1, 6)
y = randint(1, 6)
return(x, y)
## This converts the numbers into selections in the dictionary. E.G. 6 into "six" "all_dice" is ad
## and it will from now on be passed as "ad".
def dice_maker(ad,):
master = {1 : "one",
2 : "two",
3 : "three",
4 : "four",
5 : "five",
6 : "six",}
for i in range(1,2):
x = dice_roller()
y = int(x[0])
z = int(x[1])
new_die_y = (master[y])
new_die_z = (master[z])
dice_print(new_die_y,new_die_z,ad)
##This calls the script to action and passing the dictionary "all_dice"
dice_maker(all_dice)```
【问题讨论】:
-
你的字典是全球性的,你可以在任何地方直接访问它。
-
所以我一直都在想。叹。非常感谢。 :D
-
您可能想在下面查看我的答案,了解有关压缩代码的一些提示。此外,在 all_dice 中表示骰子的方式可以更简单地修改,方法是使骰子成为字符串列表而不是字符串列表。
-
通过重组你的 all_dice 字典,我能够用四行代码将你的代码重写为一个函数。
标签: python python-3.x function dictionary