LoginSignup
0
3

More than 5 years have passed since last update.

Python > 4つ以上の項目を複数のグループとして返す関数 > Named tuple

Last updated at Posted at 2017-04-06
動作環境
GeForce GTX 1070 (8GB)
ASRock Z170M Pro4S [Intel Z170chipset]
Ubuntu 14.04 LTS desktop amd64
TensorFlow v0.11
cuDNN v5.1 for Linux
CUDA v8.0
Python 2.7.6
IPython 5.1.0 -- An enhanced Interactive Python.
gcc (Ubuntu 4.8.4-2ubuntu1~14.04.3) 4.8.4
GNU bash, version 4.3.8(1)-release (x86_64-pc-linux-gnu)

Pythonで4つ以上の項目を複数のグループとして返す関数を作ってみる。

方法1 tupleをtupleする

tuple packingを使ってみた。

test_python_170407a.py
def get_tuple():
    return (3.1415, 2.718), (6.022, 10.23)

agrp, bgrp = get_tuple()
print(agrp, bgrp)

pi, napier = agrp
print(pi, napier)

avogadro_mantissa, avogadro_exponent = bgrp
print(avogadro_mantissa, avogadro_exponent)

結果
$ python test_python_170407a.py 
((3.1415, 2.718), (6.022, 10.23))
(3.1415, 2.718)
(6.022, 10.23)

一度グループとしてtuple unpackingしたものから、個々の変数を受け取るためにさらにtuple unpackingしている。

方法2 Named tuple

以下にNamed tupleを使った例がある。
http://stackoverflow.com/questions/354883/how-do-you-return-multiple-values-in-python

試してみた。

test_python_170407b.py
import collections


def get_tuple():
    Agroup = collections.namedtuple('Agroup', ['pi', 'napier'])
    agrp = Agroup(3.1415, 2.718)
    Bgroup = collections.namedtuple('Bgroup', ['mantissa', 'exponent'])
    bgrp = Bgroup(6.022, 10.23)
    return agrp, bgrp

agrp, bgrp = get_tuple()
print(agrp, bgrp)

print(agrp.pi, agrp.napier)
print(bgrp.mantissa, bgrp.exponent)
結果
$ python test_python_170407b.py 
(Agroup(pi=3.1415, napier=2.718), Bgroup(mantissa=6.022, exponent=10.23))
(3.1415, 2.718)
(6.022, 10.23)

関数呼び出し時の左側の記載が短くでき、かつ、.piや.napierのようにして、各変数の参照もしやすい。

0
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
3