如:
p={ 'a':'aa', 'b':{ 'b':'bb' } } print(dict(p).values())
回傳的是:
dict_values(['aa', {'b': 'bb'}])
而想要的是aa和bb。該怎麼寫,謝謝了
def values(d): for v in d.values(): if isinstance(v, dict): for _ in values(v): yield _ else: yield v data = values({1:1,2:{2:2,3:{3:3,4:4}}}) for v in data: print(v) # 1 2 3 4
如果使用python 3.3+,for _ in values(v): yield _ 可用 yield from values(v) 替換
for _ in values(v): yield _
yield from values(v)
貌似只能遍歷
# coding: utf-8 p={ 'a':'aa', 'b':{ 'b':'bb', 'c': { 'c': 'cc', 'd': { 'd': 'dd' } } } } def f(d): nl = [] for _ in d.values(): nl += f(_) if isinstance(_, dict) else [_] return nl print f(p)
如果使用python 3.3+,
for _ in values(v): yield _
可用yield from values(v)
替換貌似只能遍歷