2019-07-11 玩一下python3列表推导式和嵌套列表推

2019-07-19  本文已影响0人  五大RobertWu伍洋

假设 x,y,z 是三串钥匙,对应三扇门,open1 代表能打开,open0 代表不能打开。我们要找出三扇门都能打开的那把钥匙,怎么解决?

>>> ls = [('x',['open1','open1','open1']),('y',['open1','open1','open0']),('z',['open0','open0','open1'])]

>>> rs=[(x,y) for x,y in ls]
>>> rs
[('x', ['open1', 'open1', 'open1']), ('y', ['open1', 'open1', 'open0']), ('z', ['open0', 'open0', 'open1'])]

>>> rs=[(x,y) for x,y in ls if 'open1' in y]
>>> rs
[('x', ['open1', 'open1', 'open1']), ('y', ['open1', 'open1', 'open0']), ('z', ['open0', 'open0', 'open1'])]

>>> rs=[(x,y) for x,y in ls if 'open1' not in y]
>>> rs
[]

>>> rs=[(x,y) for x,y in ls if 'open0' not in y]
>>> rs
[('x', ['open1', 'open1', 'open1'])]

思考:如何循环列表将内嵌列表的第n项合并为新的列表?比如内嵌列表的第一项,然后是第二项...

>>> [y for x,y in ls]
[['open1', 'open1', 'open1'], ['open1', 'open1', 'open0'], ['open0', 'open0', 'open1']]

使用嵌套列表推导式取出字符串里的1和0再用来判断也可以:

def find(con):
    return [j for i in con for j in i if j.isdigit()]
 
[w for w,con in ls if find(con)==['1','1','1']]
>>> def find(con):
...     return [j for i in con for j in i if j.isdigit()]
...
>>> [w for w,con in ls if find(con)==['1','1','1']]
['x']

上述两个方式当然第一种的时间复杂度最小,没有嵌套循环

上一篇下一篇

猜你喜欢

热点阅读