1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Pythonの内包表記

Last updated at Posted at 2022-01-30

1. 内包表記(list)

この表記法は計算速度も速く、コードもすっきりするので覚えたほうが良いと思う記法です。

まずは、リストで作られた各値の計算

base = [0, 1, 2, 3, 4]
ret_List = []
for i in base:
    ret_List.append(i*2)
print('通常表記:', ret_List)

ret_List_comp = [i * 2 for i in base]
print('内包表記:', ret_List_comp)
通常表記: [0, 2, 4, 6, 8]
内包表記: [0, 2, 4, 6, 8]

ただ、数値を扱う場合にはnumpyを使ったほうが良いと思います。

import numpy as np
base_np = np.array([0, 1, 2, 3, 4])
ret_List = base_np * 2
print('numpy:', ret_List)
numpy: [0 2 4 6 8]

ということで、文字列を使った場合(やることは基本同じですが)によく使います。

List = ['NetSalesIFRS', 'NetSales', 'NetSalesUS']

# NetSalesを売上高に変換(通常表記)
ret_List = []
for i in List:
    ret_List.append(i.replace('NetSales', '売上高'))
print('通常表記:', ret_List)

# NetSalesを売上高に変換(内包表記)
ret_List_comp = [i.replace('NetSales', '売上高') for i in List]
print('内包表記:', ret_List_comp)
通常表記: ['売上高IFRS', '売上高', '売上高US']
内包表記: ['売上高IFRS', '売上高', '売上高US']

特定の文字列を含む場合はfor文の後にif文を入れることで対応でき来ます。

List = ['NetSalesIFRS', 'NetSales', 'NetSalesUS',
        'OperatingIncomeIFRS', 'OperatingIncome', 'OperatingIncomeUS']

# IFRSを含む文字列の抽出(通常表記)
ret_List = []
for i in List:
    if 'IFRS' in i:
        ret_List.append(i)
print('通常表記:', ret_List)

# IFRSを含む文字列の抽出(内包表記)
ret_List_comp = [i for i in List if 'IFRS' in i]
print('内包表記:', ret_List_comp)
通常表記: ['NetSalesIFRS', 'OperatingIncomeIFRS']
内包表記: ['NetSalesIFRS', 'OperatingIncomeIFRS']

リストが階層になっている場合でも内包表記は使えます。

List = [['NetSalesIFRS', 'NetSales', 'NetSalesUS'],
        ['OperatingIncomeIFRS', 'OperatingIncome', 'OperatingIncomeUS']]

# IFRSとUSを含まない文字列の抽出(通常表記)
ret_List = []
for i in List:
    for j in i:
        if ('IFRS' not in j) and ('US' not in j):
            ret_List.append(j)
print('通常表記:', ret_List)

# IFRSとUSを含まない文字列の抽出(内包表記)
ret_List_comp = [j for i in List for j in i if ('IFRS' not in j) and ('US' not in j)]
print('内包表記:', ret_List_comp)
通常表記: ['NetSales', 'OperatingIncome']
内包表記: ['NetSales', 'OperatingIncome']

2回for文を回すような時にも使えますが、1行が長くなる事があるので、短くなる工夫もあったほうが良いと思います。
例えば、上記の場合は判定条件をlambdaで別行にするとかの方法もあります。

List = [['NetSalesIFRS', 'NetSales', 'NetSalesUS'],
        ['OperatingIncomeIFRS', 'OperatingIncome', 'OperatingIncomeUS']]
jdg = lambda j :('IFRS' not in j) and ('US' not in j)
ret_List_comp_lambda = [j for i in List for j in i if jdg(j)]
print('内包表記(ラムダ):', ret_List_comp)
内包表記(ラムダ): ['NetSales', 'OperatingIncome']

2.内包表記(dict)

辞書を作成するときも、内包表記が使えます。

List = [['NetSalesIFRS', 'NetSales', 'NetSalesUS'],
        ['OperatingIncomeIFRS', 'OperatingIncome', 'OperatingIncomeUS'],
        ['OperatingIncomeToSalesRatioIFRS', 'OperatingIncomeToNetSalesRatio', 'OperatingIncomeToNetSalesRatioUS']]
key = ['売上高', '営業利益', '営業利益率']

ret_Dict = {}
for k, v in zip(key, List):
    ret_Dict[k] = v
print('通常表記:', ret_Dict)

ret_Dict_comp = {k: v for k, v in zip(key, List)}
print('内包表記:', ret_Dict_comp)
通常表記: {'売上高': ['NetSalesIFRS', 'NetSales', 'NetSalesUS'], '営業利益': ['OperatingIncomeIFRS', 'OperatingIncome', 'OperatingIncomeUS'], '営業利益率': ['OperatingIncomeToSalesRatioIFRS', 'OperatingIncomeToNetSalesRatio', 'OperatingIncomeToNetSalesRatioUS']}
内包表記: {'売上高': ['NetSalesIFRS', 'NetSales', 'NetSalesUS'], '営業利益': ['OperatingIncomeIFRS', 'OperatingIncome', 'OperatingIncomeUS'], '営業利益率': ['OperatingIncomeToSalesRatioIFRS', 'OperatingIncomeToNetSalesRatio', 'OperatingIncomeToNetSalesRatioUS']}

辞書のフォーマットを作ったりするときにも使えます。

l = ['A', 'B', 'C']
m = ['a', 'b', 'c']
Dict = {k: {kk: [] for kk in m} for k in l }
print(Dict)
{'A': {'a': [], 'b': [], 'c': []}, 'B': {'a': [], 'b': [], 'c': []}, 'C': {'a': [], 'b': [], 'c': []}}
1
1
1

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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?