Doubt in Python FOR cycle
I'm with some doubts in a Python FOR cycle:
This code works great:
a, b, c, d, e, f, g, h = range(8)
_ = float('inf')
# a b c d e f g h
W = [
[0,2,1,3,9,4,_,_], # a
[_,0,4,_,3,_,_,_], # b
[_,_,0,8,_,_,_,_], # c
[_,_,_,0,7,_,_,_], # d
[_,_,_,_,0,5,_,_], # e
[_,_,2,_,_,0,2,2], # f
[_,_,_,_,_,1,0,6], # g
[_,_,_,_,_,9,8,0]] # h
sum(1 for w in W[a] if w < _) - 1 # Degree
My question is:
The the "FOR x IN y IF x < 10" only works inside a SUM?
I have tested this but it does not work:
a, b, c, d, e, f, g, h = range(8)
_ = fl开发者_如何学编程oat('inf')
# a b c d e f g h
W = [
[0,2,1,3,9,4,_,_], # a
[_,0,4,_,3,_,_,_], # b
[_,_,0,8,_,_,_,_], # c
[_,_,_,0,7,_,_,_], # d
[_,_,_,_,0,5,_,_], # e
[_,_,2,_,_,0,2,2], # f
[_,_,_,_,_,1,0,6], # g
[_,_,_,_,_,9,8,0]] # h
for w in W[a] if w < _:
print 1
Best Regards,
Try:
for k in [w for w in W[a] if w < _]:
print 1
You need to use the if
clause within a list comprehension (but as noted in the comment, this is not the optimal way to do this).
Edit: If you are looking to learn some of the 'awesome' features of python, you could also try using itertools
:
for k in itertools.ifilter(lambda x: x < _ ,W[0]):
print 1
There are many other solutions, some more or less elegant and efficient than others. If you want to get really awesome and you are basically using array structures, look into numpy
to unlock a whole world of elegance and speed.
AFAIK, the if clause in the for statement is only allowed in list comprehension or generator expression. See http://docs.python.org/reference/compound_stmts.html#the-for-statement
精彩评论