11/29/2018

Python Notes (2)

1. Sort: 
  • sorted() vs list.sort()
    • Sorted() returns a new list vs list.sort() does in place. 
    • list.sort() only for list. But sorted() for all iterables. 
  • key function and (reverse=True)
  • Sorted by multiple elements, like by first item then 2nd. 
>>> p = [[1,2,3],[3,2,1],[2,4,6],[1,2,5],[1,3,7],[3,1,0],[1,7,2]]
>>> p.sort(key=lambda x:(x[0], x[2]))
>>> p
[[1, 7, 2], [1, 2, 3], [1, 2, 5], [1, 3, 7], [2, 4, 6], [3, 1, 0], [3, 2, 1]]
  • Sorted by reversed plus asc
>>> p = [[1,2,3],[3,2,1],[2,4,6],[1,2,5],[1,3,7],[13,1,0],[-1,7,2]]
>>> p.sort(key=lambda x:(-x[0], x[2]))
>>> p
[[13, 1, 0], [3, 2, 1], [2, 4, 6], [1, 2, 3], [1, 2, 5], [1, 3, 7], [-1, 7, 2]]


2. SET:

1) No duplicate
2) No order
3) Sets contain only hashable items, for __contain__ method
4) Sets have operator like "-"

_set = set([1,2,3,3]) # (1,2,3)


s1 = set([1,2,3,4])
s2 = set([2,3,5])

l1 = [1,2,3,4]
l2 = [2,3,5]
s1 - s2
set([1, 4])


l1 - l2
Error

3. Variable length arguments in function call

positional argument with unknown number of arguments
def __func__(*args):
    for count, item in enumerate(args):
        print '{0}. {1}'.format(count, thing)

named arguments
def __func__(**kwargs):
    for name, value in kwargs.items():
        print '{0} = {1}' % (name, value)

TCL:
proc __proc__ {first args} {}

4. How to re-import python module in interactive mode
>>> from myrange import *
>>> for i in myrange(1,3,1):
...     print i
...
1 <<<<< extra print out due to debug print
1
2

$ more myrange.py
class myrange:
    def __init__(self, start, end, step):
        self.start = start
        self.end = end
        self.step = step
        print self.step   <<<< need to remove this

Change the py file, and do 2 steps



>>> import myrange   <<< need to import module for reload()
>>> reload(myrange)
<module 'myrange' from 'myrange.py'>
>>> from myrange import *
>>> for i in myrange(1,3,1):
...     print i
...
1  <<<< corrected
2

5. Python class class/instance/internal variables

啥叫class/instance/internal variables? 
- classVar 是Object之间share,一个改,大家都改,也叫Static variable
- instanceVar,所以叫Self.instanceVar,就是object自己本地
- internal,就不说了

class Obj(object):
    classVar = [10,20,30]
    def __init__(self):
        self.instanceVar = [1,2,3]
        internalVar = [100,200,300]

o1 = Obj()
o2 = Obj()

o1.instanceVar.append(11)
o1.instanceVar.append(12)
o2.instanceVar.append(21)
o2.instanceVar.append(22)

print o1.instanceVar
print o2.instanceVar

o1.classVar.append(111)
o2.classVar.append(222)
print o1.classVar
print o2.classVar

No comments:

Post a Comment