Есть ли простой способ ввести словарь в функцию? - PullRequest
0 голосов
/ 16 февраля 2020

Цель состоит в том, чтобы поиграть в крэпс с этим.

Я создал словарь "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)```

Ответы [ 2 ]

2 голосов
/ 16 февраля 2020

Вы можете полностью отбросить его как параметр.

A python модуль ведет себя очень похоже на одноэлементный класс. Модуль, как и класс, является объектом. all_dice является атрибутом модуля и, следовательно, доступен для функций, относящихся к тому же модулю.

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):
    x = 0
    nday = all_dice[ndy]
    ndaz = all_dice[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():
    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)


##This calls the script to action and passing the dictionary "all_dice"

dice_maker()

Ключевое слово global

Если вам требуется переназначить all_dice в функция. Вы должны добавить global all_dice к функции.

all_dice = None

def set_all_dice(value):
    global all_dice
    all_dice = value

def _set_all_dice(value):
    all_dice = value       ## all_dice here is scoped to the function
1 голос
/ 16 февраля 2020

Вы можете сжать большую часть этого кода. Функция, которая печатает, может быть сжата с помощью '' .join () и понимания списка. И функция dice_roller (), состоящая всего из нескольких строк активного кода, может быть просто включена в основную функцию.

>>> def roll():
...     num_words = ["dummy", "one", "two", "three", "four", "five", "six"]
...     x = randint(1, 6)
...     y = randint(1, 6)
...     d1 = all_dice[num_words[x]]
...     d2 = all_dice[num_words[y]]
...     roll_str = ''.join(["%s %s\n" % (d1[i][0], d2[i][0]) for i in range(5)])
...     print(roll_str)
>>> roll()
_____ _____
0     0   0
        0  
    0 0   0
_____ _____

Повторно реализуя all_dice следующим образом:

all_dice = {6: ["____", "0  0", "0  0", "0  0", "____"], 5: <and so on...>

Код упрощенно:

>>> def roll():
...     d1 = all_dice[randint(1, 6)]
...     d2 = all_dice[randint(1, 6)]
...     print(''.join(["%s %s\n" % (d1[i], d2[i]) for i in range(5)]))
>>> roll()
_____ _____
0     0   0
        0  
    0 0   0
_____ _____
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...