列表理解中的'while'? [英] 'while' in list comprehension?
问题描述
你好,
除了
''之外还有一个''while''条件是否有用'''''在列表推导中?
foo = []
for i in bar:
if len(i)== 0:
休息
foo.append(i)
然后变成
foo = [i for i in bar而len(i)> 0]
有没有理由没有这种东西?我实际上很多时候会错过它。
干杯,jsaul
jsaul问...然后会变成
foo = [i for i in bar而len(i)> 0]
>有没有理由没有这种东西?我实际上经常想念它。
这有什么不同:
foo = [i for i in bar in if len(i)]
Emile van Sebille
em *** @ fenx.com
foo = [i for i in bar而len(i)> 0 ]
Emile>这有什么不同:
Emile> foo = [i for i in bar if len(i)]
第一个是:
_ = []
for i in bar:
if if(len(i)> 0):
break
_.append (i)
返回_
第二个是:
_ = []
for i in bar:
if len(i)> 0:
_.append(i)
返回_
跳过
使用2.3'的itertools:
foo = [i for ite in itertools.takewhile(lambda i:len(i)> 0,bar)]
或者
foo = list(itertools.takewhile(len,bar)]
甚至
foo = itertools .takewhile(len,bar)#a iterable,not a list
Jeff
Hi there,
wouldn''t it be useful to have a ''while'' conditional in addition to
''if'' in list comprehensions?
foo = []
for i in bar:
if len(i) == 0:
break
foo.append(i)
would then turn into
foo = [ i for i in bar while len(i)>0 ]
Is there any reason for not having this kind of thing? I actually
miss it pretty often.
Cheers, jsaul
jsaul asks...would then turn into
foo = [ i for i in bar while len(i)>0 ]
Is there any reason for not having this kind of thing? I actually
miss it pretty often.
How is this different from:
foo = [ i for i in bar if len(i) ]
Emile van Sebille
em***@fenx.com
foo = [ i for i in bar while len(i)>0 ]
Emile> How is this different from:
Emile> foo = [ i for i in bar if len(i) ]
The first is like:
_ = []
for i in bar:
if not (len(i) > 0):
break
_.append(i)
return _
The second is like:
_ = []
for i in bar:
if len(i) > 0:
_.append(i)
return _
Skip
Use 2.3''s itertools:
foo = [i for i in itertools.takewhile(lambda i: len(i) > 0, bar)]
or maybe
foo = list(itertools.takewhile(len, bar)]
or even
foo = itertools.takewhile(len, bar) # an iterable, not a list
Jeff
这篇关于列表理解中的'while'?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!