Python Skills

  • Summary
  • the peculiar nature of and and or
    • 1 and
    • or
  • Conditional Assignment
  • set builtin

Summary

  1. avoid "for" and "if-and-else"
    instead, use list comprehension and conditional
    assignment
  2. fs

1. the peculiar nature of ‘and’ and ‘or’

Citation.

Unlike other language, python will not only perform boolean, but also return one of the actual values they are comparing.

1.1 and

>>  'a' and 'b'
'b'
>> '' and 'b'
''
>> 'a' and 'b' and 'c'
'c'

python regards 0, ”, [], (), {} and None be false. everything else is true.

For ‘and’, it will return the first false value if any value is false in the boolean context, or return the last value if all of them are true

or

>>> 'a' or 'b'
'a'
>>> '' or 'b'
'b'
>>> '' or [] or {}
{}

or operator is different from and operator. It will return the last value if all values are false, or return the first true value ( ignore the rest ) if any value is true.

2. Conditional Assignment

Citation

x = 3 if (y == 1) else 2

It does exactly what is sounds like

if y==1:
    x = 3
else:
    x = 2

more complicated

x = 3 if (y == 1) else 2 if (y == -1) else 1
if y==1:
    x = 3
else:
    if y==-1:
        x = 2
    else:
        x = 1

Good example, for function

x = (func1 if y == 1 else func2)(arg1, arg2) 

3. set builtin

Citation

>>> a = set([1,2,3,4])
>>> b = set([3,4,5,6])
>>> a | b   #Union
{1,2,3,4,5,6}
>>> a & b   #Intersection
{3, 4}
>>> a < b   #Subset
False
>>> a & b   #Symmetric Difference
{1, 2, 5, 6}
>>> a - b   #Difference
{1, 2}

你可能感兴趣的:(Python Skills)