Data Collection and Processing with Python: week2: nested itemsとzip function

Extraction from nested data

 

dictionaryをlist化する方法

nested_d = {‘Beijing’:{‘China’:51, ‘USA’:36, ‘Russia’:22, ‘Great Britain’:19},
‘London’:{‘USA’:46, ‘China’:38, ‘Great Britain’:29, ‘Russia’:22},
‘Rio’:{‘USA’:35, ‘Great Britain’:22, ‘China’:20, ‘Germany’:13}}

L = nested_d[“London”]
print(L)
for i in L:
print(i, L[i])

lst = []
for i in L:
lst.append([i, L[i]])
print(lst)

nested dictionary から必要な情報だけ取り出す方法

nested_d = {‘Beijing’:{‘China’:51, ‘USA’:36, ‘Russia’:22, ‘Great Britain’:19},
‘London’:{‘USA’:46, ‘China’:38, ‘Great Britain’:29, ‘Russia’:22},
‘Rio’:{‘USA’:35, ‘Great Britain’:22, ‘China’:20, ‘Germany’:13}}

US_count = []
for dic in nested_d.keys():
print(nested_d[dic])
print(nested_d[dic][“USA”])

for dic in nested_d.keys():
US_count.append(nested_d[dic][“USA”])

 

athletes = [[‘Phelps’, ‘Lochte’, ‘Schooling’, ‘Ledecky’, ‘Franklin’],
[‘Felix’, ‘Bolt’, ‘Gardner’, ‘Eaton’],
[‘Biles’, ‘Douglas’, ‘Hamm’, ‘Raisman’, ‘Mikulak’, ‘Dalton’]]
t = []
other = []
for lst in athletes:
for i in range(len(lst)):
if “t” in lst[i]:
t.append(lst[i])
else:
other.append(lst[i])

 

nested dataをjsonでdumps()してdictionaryにして読み込み、keyやらlenやらで中身を探りextractする。structureがわかれば、探れる。

Nested list = Lists, dictionary, and function in a list

How to extract data?

新事実。fileにはstriingしか書き込めない????

 

dictionaryよりも便利かも。

Mutateされます。

nested1 = [[‘a’, ‘b’, ‘c’],[‘d’, ‘e’],[‘f’, ‘g’, ‘h’]]
print(id(nested1))
print(nested1[0])
print(nested1[1])
print(nested1[2][1]) #double indexing
print(len(nested1))
nested1.append([‘i’, ‘y’])
print(“——-“)
for L in nested1:
print(L)
print(“——-“)
nested1[2][1] = 100
nested1[0] = [3,4]
for L in nested1:
print(L)
print(id(nested1))

functionもlistの中に入る。

for statementが使えない状況に注意。

Shallow Copies and deep copies

deepcopy使わないでcopyしようとするとこうなります。

 

Nested dictionary = dictionary in dictionary

dictionaryといえば.items()でtuple取得。

d = {‘key1’: {‘a’: 5, ‘c’: 90, 5: 50},
‘key2’:{‘b’: 3, ‘c’: “yes”}}
d[“key3”] = {1: 2, 3: 4}#dの第一層に{“key3”: {1: 2, 3: 4}}を追加。
d[‘key1’][‘d’] = d[‘key2’]#dのkey1内に{“d”: {‘b’: 3, ‘c’: “yes”}}を追加。
for ds in d.items():
print(ds)

一つづつkeyを特定していく。

JSON format は nested dictionary

JSON Editor Online: edit JSON, format JSON, query JSON
JSON Editor Online is the original and most copied JSON Editor on the web. Use it to view, edit, format, repair, compare...

json.loads(obj)はfile→python

json moduleのloads()メソッドはstringをdict or listにする。

fileに書き込まれていたstringの情報をpythonで使用可能にするための処理に使える。

import json

json.loads(string)で起動

json.dumps()はpython→file

json moduleのdumps()メソッドはlist, dictionaryをstringにする。

pythonで処理したデータをfileに書き直すときに使えそう。

import json

json.dumps(list_or_dictionary)で起動

Map, Filter, List Comprehensions, and Zip

Python provides built-in functions map and filter. Python also provides a new syntax, called list comprehensions, that lets you express a mapping and/or filtering operation.

map()は関数によってvalueを変える。

手動でやるとこうなる。

 

list(map())でmapは新しいidのsequenceを生成する。

print(“map()の第一argumentは関数。第二はsequence”)
print(“map()はitelateするが、listをreturnしないのでlist()でリスト化する”)
def triple(value):
return 3*value

def tripleStuff(a_list):
new_seq = map(triple, a_list)
return list(new_seq)

def quadrupleStuff(a_list):
new_seq = map(lambda value: 4*value, a_list)
return list(new_seq)

things = [2, 5, 9]
things0 = things[:]

print(things0)
print(map(triple, things0))
print(list(map(triple, things0)))

things3 = tripleStuff(things)
print(things3)
things4 = quadrupleStuff(things)
print(things4)

 

lst_check = [‘plums’, ‘watermelon’, ‘kiwi’, ‘strawberries’, ‘blueberries’, ‘peaches’, ‘apples’, ‘mangos’, ‘papaya’]

def hoge(hoge):
return “Fruit: ” + hoge

map_testing = list(map(hoge, lst_check))

print(map_testing)

 

filterはsequenceから関数のブーリアン値がtrueとなるものを新しいid付きで生成する。

手動だとこうなる。

print(“filer()も関数の外で単独で使うならリスト化しないと出てこない。”)
def keep_evens(nums):
new_seq = filter(lambda num: num % 2 == 0, nums)
return list(new_seq)
lst1 = [3, 4, 6, 7, 0, 1]
print(keep_evens(lst1)) #関数内でfilterを使用するならlist化しなくていい。
print(filter(lambda num: num % 2 == 0, lst1))
print(list(filter(lambda num: num % 2 == 0, lst1)))
print(id(lst1))
print(id(keep_evens(lst1)))
print(id(list(filter(lambda num: num % 2 == 0, lst1))))

filter(lambda x:のxは勝手に第二argumentのsequenceのアイテムになる

print(“filter(lambda x:のxは勝手に第二argumentのsequenceのアイテムになる)”)
lst_check = [‘plums’, ‘watermelon’, ‘kiwi’, ‘strawberries’, ‘blueberries’, ‘peaches’, ‘apples’, ‘mangos’, ‘papaya’]

print(“filter()もlist化しないと出てきません。”)
filter_testing = filter(lambda hoge: “w” in hoge, lst_check)

print(filter_testing)
print(list(filter_testing))

map()の第二argumentでfilerをかけることもできる

23.4. List Comprehensions はlist = [], append(), map(), filter()のalternative!!!

hogeはsequenceのitemを取ってくる。sequence中の何をiterateするか指定する。

things = [3, 4, 6, 7, 0, 1]

#functionを使った場合。
def keep_evens(hoge):
new_list = [hoge * 2 for hoge in things if hoge % 2 == 0]
return new_list
print(keep_evens(things))

#map(), filter()を使った場合。
print(list(map(lambda hoge: hoge*2,
filter(lambda hoge: hoge % 2 == 0, things))))

#list comprehensionを使った場合。
print([hoge*2 for hoge in things if hoge % 2 == 0])

 

list comprehensionはblank_list.append()、for statementを省略する。

tester = {‘info’: [
{“name”: “Lauren”, ‘class standing’: ‘Junior’, ‘major’: “Information Science”},
{‘name’: ‘Ayo’, ‘class standing’: “Bachelor’s”, ‘major’: ‘Information Science’},
{‘name’: ‘Kathryn’, ‘class standing’: ‘Senior’, ‘major’: ‘Sociology’},
{‘name’: ‘Nick’, ‘class standing’: ‘Junior’, ‘major’: ‘Computer Science’},
{‘name’: ‘Gladys’, ‘class standing’: ‘Sophomore’, ‘major’: ‘History’},
{‘name’: ‘Adam’, ‘major’: ‘Violin Performance’, ‘class standing’: ‘Senior’}]}
tester_v = tester[“info”]
print(tester_v)

#今までの方法
compri = []
for i in tester_v:
print(i[“name”])
compri.append(i[“name”])
print(compri)

#compri = [] もappend()もいらない。
#i_dict[“name”]で、sequence中の何をiterateするか指定する。
compri = [i_dict[“name”] for i_dict in tester[“info”]]
print(compri)

json.dumps(dictionary, indent = 2)で辞書の構造を掴め!

 

zip functionは同じidを持つ異なるsequenceの要素のtupleを作る。

zip functionはsequenceの各要素の同じidを組み合わせてtupleを作る。

L1 = [3, 4, 5]
L2 = [1, 2, 3]
L3 = []

print(“zip functionはsequenceの各要素の同じidを組み合わせてtupleを作る。”)
L4 = list(zip(L1, L2))
print(type(zip(L1, L2)))
print(L4)

for x1, x2 in L4: #for statement内でtupleの要素を取得できる件
L3.append(x1+x2)
print(L3)

#list compregensionを使うとこうなる。
L5 = [x1 + x2 for (x1, x2) in list(zip(L1, L2))]
print(L5)

print(“   strでもzip functionでtuple作れる?作れました。”)
s1 = “adf”
s2 = “kno”
s4 = list(zip(s1, s2))
print(s4)

print(” tupleにzip functionは使えるか?使えました。”)
t1 = (4, 7)
t2 = (5, 6)
print(list(zip(t1, t2)))

print(” dictionaryにzip functionは使えるか?使えました。”)
d1 = {“name1” : {“a”: 1, “b”: 2}}
d2 = {“name2” : {“a”: 3, “b”: 4}}
print(list(zip(d1, d2)))#(di1.keys(), d2.keys())と同じ。
print(list(zip(d1.values(), d2.values())))
print(list(zip(d1.items(), d2.items())))

 

 

 

 

 

コメント