Python
 Computer >> コンピューター >  >> プログラミング >> Python

任意の数の引数を受け入れるPythonで関数を作成する方法


問題

任意の数の入力引数を受け入れる関数を作成したい。

解決策

Pythonの*引数は、任意の数の引数を受け入れることができます。これは、与えられた2つ以上の数値の平均を求める例で理解できます。以下の例では、rest_argは、渡されたすべての追加の引数(この場合は番号)のタプルです。この関数は、平均計算を実行する際に引数をシーケンスとして扱います。

# Sample function to find the average of the given numbers
def define_average(first_arg, *rest_arg):
average = (first_arg + sum(rest_arg)) / (1 + len(rest_arg))
print(f"Output \n *** The average for the given numbers {average}")

# Call the function with two numbers
define_average(1, 2)

出力

*** The average for the given numbers 1.5


# Call the function with more numbers
define_average(1, 2, 3, 4)

出力

*** The average for the given numbers 2.5

任意の数のキーワード引数を受け入れるには、**で始まる引数を使用します。

def player_stats(player_name, player_country, **player_titles):
print(f"Output \n*** Type of player_titles - {type(player_titles)}")
titles = ' AND '.join('{} : {}'.format(key, value) for key, value in player_titles.items())

print(f"*** Type of titles post conversion - {type(titles)}")
stats = 'The player - {name} from {country} has {titles}'.format(name = player_name,
country=player_country,
titles=titles)
return stats

player_stats('Roger Federer','Switzerland', Grandslams = 20, ATP = 103)

出力

*** Type of player_titles - <class 'dict'>
*** Type of titles post conversion - <class 'str'>


'The player - Roger Federer from Switzerland has Grandslams : 20 AND ATP : 103'

上記の例では、player_titlesは渡されたキーワード引数を保持する辞書です。

任意の数の位置引数とキーワードのみの引数の両方を受け入れることができる関数が必要な場合は、*と**を一緒に使用してください

def func_anyargs(*args, **kwargs):
print(args) # A tuple
print(kwargs) # A dict

この関数を使用すると、すべての位置引数がタプル引数に配置され、すべてのキーワード引数が辞書kwargsに配置されます。


  1. Pythonはどのように乱数を生成しますか?

    Pythonの標準配布には、乱数生成機能を備えたランダムモジュールがあります。基本的なrandom()関数は、0から1までのランダムな浮動小数点数を返します >>> import random >>> random.random() 0.5204702770265925 同じモジュールから、連続する範囲の間の乱数を返すrandrange()関数があります。 >>> random.randrange(0,10) 4 リストまたはタプルからアイテムをランダムに選択するchoice()関数もあります >>> random.ch

  2. Python関数の引数の数を見つけるにはどうすればよいですか?

    次のようなスクリプトqux.pyがあるとします #qux.py def aMethod1(arg1, arg2):      pass def aMethod2(arg1,arg2, arg3, arg4, arg5):     pass このスクリプトの内容にアクセスできないと仮定すると、次のように、指定された関数の引数の数を見つけることができます Python関数内のパラメーター名のリストを見つけるには、inspectモジュールをインポートし、指定されたスクリプトqux.pyもインポートします。 inspect.getargspec(