d**********n 发帖数: 1 | 1 如题
需要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 不考虑。 | d*******n 发帖数: 43 | 2 直接当string处理 遇到chess就去找下一个name? | d**********n 发帖数: 1 | 3 你能直接上code吗
我以下这行这个code只能解决 regular nested,一旦不regular nested的歇菜
print( [b['name'] for a in data for b in a if b['Hobby']=='chess'] )
【在 d*******n 的大作中提到】 : 直接当string处理 遇到chess就去找下一个name?
| x******a 发帖数: 6336 | 4 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'] | x********o 发帖数: 2092 | 5 [d['name'] for x in data for d in (x if isinstance(x,list) else (x,)) if d['
Hobby']=='chess'] | d**********n 发帖数: 1 | 6 感觉你这个就是把flatten 递归函数写成一行的代码了
我之前想法是先写个递归函数,在filter,面官说不work
is
dict
【在 x******a 的大作中提到】 : 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**********n 发帖数: 1 | 7 work 你这个是可接受的答案
['
【在 x********o 的大作中提到】 : [d['name'] for x in data for d in (x if isinstance(x,list) else (x,)) if d[' : Hobby']=='chess']
|
|