2017-01-20 2 views
6

ich das folgende tue:Eine Verknüpfung Aussagen über die ‚und‘ Schlüsselwort

if ycoords[0] > 0 and ycoords[1] > 0 and ycoords[2] > 0: 
    # do stuff 

Können Sie diesen Code wie, indem Sie etwas verkürzen: Ja

if (ycoords[0] and ycoords[1] and ycoords[2]) > 0: 
    # do stuff 
+0

Auch verwandt: http://stackoverflow.com/questions/10666163/how-to-check-if-all-elements-of-a-list-matches-a-condition –

Antwort

9

Sie all verwenden:

if all(x > 0 for x in ycoords): 

oder ycoords[:3] wenn ycoords mehr als 3 Elemente hat.

3

Nein, können Sie jedoch einfach min verwenden den Test syntaktisch zu vereinfachen:

if min(ycoords[0],ycoords[1],ycoords[2]) > 0: 
    # do stuff 

und da ycoords genau drei Elemente hat, noch kürzer:

if min(*ycoords) > 0: 
    #do stuff 

Sie können hier, wie @ Tagc sagt, das Sternchen weglassen (*):

if min(ycoords) > 0: 
    #do stuff 

, aber dies wird zu einem Mehraufwand führen.

Eine weitere Option ist ein verwenden all:

if all(x > 0 for x in [ycoords[0],ycoords[1],ycoords[2]]): 
    # do stuff 

oder wieder, wenn ycoords nur diese drei Elemente enthält:

if all(x > 0 for x in ycoords): 
    # do stuff 
+3

"noch kürzer:' wenn min (* ycoords)> 0' ". Und * sogar * kürzer: 'if min (ycoords)> 0'. – Tagc

1

Etwas, das nicht intuitiv ist, dass and:

"weder noch noch oder den Wert beschränken und geben Sie sie auf False True zurück, aber eher das letzte ausgewertet Argument zurückgeben“

Nur ein Python-Terminal öffnen und zu tun:

>> 4 and 3 
3 

Warum ist das ist wichtig zu berücksichtigen?

Man könnte denken, dass:

ycoords[0] > 0 and ycoords[1] > 0 and ycoords[2] > 0 

oder das entspricht:

(bool(ycoords[0]) and bool(ycoords[1]) and bool(ycoords[2])) > 0 

aber es ist stattdessen gleich:

(ycoords[0] and ycoords[1] and ycoords[2]) > 0 

äquivalent ist

ycoords[2] > 0 

Also, sei vorsichtig, weil der Interpreter nicht tut, was du denkst.

Verwandte Themen