how about this? names = [ e['name'] for sublist in data for e in sublist if type(sublist) is list and e['Hobby']=='chess'] + [e['name'] for e in data if type(e) is dict and e['Hobby']=='chess']
感觉你这个就是把flatten 递归函数写成一行的代码了 我之前想法是先写个递归函数,在filter,面官说不work 【 在 xiaojiya (xiaojiya) 的大作中提到: 】 : how about this? : names = [ e['name'] for sublist in data for e in sublist if type(sublist) is : list and e['Hobby']=='chess'] + [e['name'] for e in data if type(e) is dict : and e['Hobby']=='chess']
如题
需要2分钟以内解决,一行code
data=[
[{'Hobby':'chess','name':'wang'}],[{'Hobby':'football','name':'zhang'}],
[{'Hobby':'chess','name':'xixi'}],[{'Hobby':'chess','name':'hehe'}],
[{'Hobby':'football','name':'dd'},{'Hobby':'football','name':'fafa'}],
[{'Hobby':'football','name':'12'},{'Hobby':'chess','name':'f3'}],
{'Hobby':'chess','name':'fa'},[{'Hobby':'football','name':'ht44g'}]
]
注意是不规则nested,即有的元素是一维nest,有的2维,不确定的。
一行代码输出所有hobby 是chess的 name
先写function 转nested为flatten 再filter 这个solution 不考虑。
直接当string处理 遇到chess就去找下一个name?
你能直接上code吗
我以下这行这个code只能解决 regular nested,一旦不regular nested的歇菜
print( [b['name'] for a in data for b in a if b['Hobby']=='chess'] )
【 在 dabaojian (蔡宝健不刷题了,兄弟们再见) 的大作中提到: 】
: 直接当string处理 遇到chess就去找下一个name?
how about this?
names = [ e['name'] for sublist in data for e in sublist if type(sublist) is list and e['Hobby']=='chess'] + [e['name'] for e in data if type(e) is dict and e['Hobby']=='chess']
[d['name'] for x in data for d in (x if isinstance(x,list) else (x,)) if d['Hobby']=='chess']
感觉你这个就是把flatten 递归函数写成一行的代码了
我之前想法是先写个递归函数,在filter,面官说不work
【 在 xiaojiya (xiaojiya) 的大作中提到: 】
: how about this?
: names = [ e['name'] for sublist in data for e in sublist if type(sublist) is
: list and e['Hobby']=='chess'] + [e['name'] for e in data if type(e) is
dict
: and e['Hobby']=='chess']
work 你这个是可接受的答案
【 在 xiaoduoduo (水佬倌) 的大作中提到: 】
: [d['name'] for x in data for d in (x if isinstance(x,list) else (x,)) if d['
: Hobby']=='chess']