変数に割り当てられるコードの繰り返しを減らすための関数を作成しようとしています。
現在、これを行うと動作します
from pyquery import PyQuery as pq
import pandas as pd
d = pq(filename='20160319RHIL0_edit.xml')
# from nominations
res = d('nomination')
nomID = [res.eq(i).attr('id') for i in range(len(res))]
horseName = [res.eq(i).attr('horse') for i in range(len(res))]
zipped = list(zip(nomID, horseName))
frames = pd.DataFrame(zipped)
print(frames)
この出力を生成します。
In [9]: 0 1
0 171115 Vergara
1 187674 Heavens Above
2 184732 Sweet Fire
3 181928 Alegria
4 158914 Piamimi
5 171408 Blendwell
6 166836 Adorabeel (NZ)
7 172933 Mary Lou
8 182533 Skyline Blush
9 171801 All Cerise
10 181079 Gust of Wind (NZ)
ただし、これに追加し続けるには、このような変数をさらに作成する必要があります(以下)。この場合、唯一の変更部分は変数名と属性です attr( 'horse' )
horseName = [res.eq(i).attr('horse') for i in range(len(res))]
したがって、DRYして、属性のリストである引数を取る関数を作成するのは論理的です
from pyquery import PyQuery as pq
import pandas as pd
d = pq(filename='20160319RHIL0_edit.xml')
# from nominations
res = d('nomination')
aList = []
def inputs(args):
'''function to get elements matching criteria'''
optsList = ['id', 'horse']
for item in res:
for attrs in optsList:
if res.attr(attrs) in item:
aList.append([res.eq(i).attr(attrs) for i in range(len(res))])
zipped = list(zip(aList))
frames = pd.DataFrame(zipped)
print(frames)