【问题标题】:python: pass multiple arguments from one function to anotherpython:将多个参数从一个函数传递给另一个函数
【发布时间】:2012-08-02 13:18:23
【问题描述】:

我正在尝试学习 Python(具有 VBA 背景)购买构建二十一点游戏作为教学练习。

我已经进行了一些关于传递多个参数的搜索,但我真的不明白我在解释的方式中发现了什么。

查看最后一个名为“hand”的函数,我试图利用三个单独的值作为前一个函数的“return”传递。

我收到以下错误:

Traceback (most recent call last):
File "decky15.py", line 56, in <module>
print hand(deal(shuffle(load_deck())))
TypeError: hand() takes exactly 3 arguments (1 given)

我做错了什么?我怎样才能更有效率?非常感谢任何有关解决方案或读数的建议。

import random


def load_deck():
    suite = ('Spades', 'Hearts', 'Diamonds', 'Clubs')
    rank = ('2', '3', '4', '5', '6', '7', '8', '9', '10', "Jack", "Queen", "King", "Ace")
    full_deck = {}
    i = 0
    for s in suite:
        for r in rank:
            full_deck[i] = "%s of %s" % (r, s)
            i += 1
    return full_deck

def pick_item(dict_in_question):   
    card_key = random.choice(dict_in_question.keys()) 
    card = dict_in_question[card_key]  
    del dict_in_question[card_key]  
    return card

def shuffle(dict_in_question):  #takes a dictionary as an argument and shuffles it
    shuff_dict = {}
    n = len(dict_in_question.keys())
    for i in range(0, n):
        shuff_dict[i] = pick_item(dict_in_question)
    return shuff_dict

def deal(dict_in_question):
dealer ={}
player = {}
for i in range (2):
    player[i] = pick_item(dict_in_question)
        dealer[i] = pick_item(dict_in_question)
return (player, dealer, dict_in_question)

def hand(player, dealer, dict_in_question):
print"Here are the opening hands:"
print"Dealer: %s" % dealer(1)
print" - " * 10
print"Your hand:"
print"%s" % player[0]
print"%s" % player[1]
return 0

print hand(deal(shuffle(load_deck())))  #changed to: hand(*deal(shuffle(load_deck())))

【问题讨论】:

  • @klobucar 现在我得到“无”返回。我怎样才能得到打印件?
  • @klobucar:“python 函数默认返回 true”。不,他们默认返回None
  • 我如何摆脱无?
  • 如果您不想打印来自hand() 的返回值,只需调用hand(deal(shuffle(load_deck()))) 而不使用打印语句。
  • 呃,我措辞不好。我的意思是丢失“返回 0”,因为 python 函数总是返回一些东西并在最后丢失打印。

标签: python function argument-passing


【解决方案1】:

试试print hand(*deal(shuffle(load_deck())))

* 告诉 python 做argument unpacking

【讨论】:

  • 顺便问一下,有没有更好的方法来调用函数?即没有 3 个嵌套函数?
  • 对我来说似乎很好——它是实用的风格。我想你可以合并这些函数,这样你就只有一个电话;或者使用一些变量来存储返回的结果...
  • 哇刚刚知道为什么你把* 放在*args 声明中。我在没有* 的情况下将args 从一个函数传递到下一个函数,并且得到一个元组,其中一个元素包含整个args 元组。谢谢!
猜你喜欢
  • 1970-01-01
  • 2019-07-25
  • 2012-09-25
  • 2020-10-03
  • 1970-01-01
  • 2013-11-19
  • 1970-01-01
相关资源
最近更新 更多