Tips for python

  1. How to reverse a list:
    1
    2
    3
    4
    list = "test1"
    print list[::-1]
    # list[a:b:c] ,out put range from [a,b), with step C
    #output: "1tset"
  2.  

  3. Python pass list by reference, so if you write something like :
    1
    2
    3
    4
    5
    a = [1]
    b=a
    b.append(2)
    print a
    #output: [1, 2]
  4.  

  5. List addition:
    1
    2
    print [1,2]+[2,3]
    #output: [1, 2, 2, 3]
  6.  

  7. Zip and unzip:
    1
    2
    3
    4
    5
    6
    7
    8
    x = [1, 2, 3]
    y = [4, 5, 6]
    zipped = zip(x, y)
    print zipped
    # [(1, 4), (2, 5), (3, 6)]
    x2, y2 = zip(*zipped) #* means unzip
    print x == list(x2) and y == list(y2)
    # True
  8.  

  9. How to realize stack in python:
    1
    2
    3
    4
    5
    li = []
    li.append(1)
    t = li.pop()
    print t==1, li
    #output True, []
  10.  

  11. String split and join:
    1
    2
    3
    4
    5
    6
    7
    a = "a/b/cde/fg"
    t = a.split("/")
    print t
    #["a", "b", "cde", "fg"]
    another = "/".join(t)
    print another == a
    #True

发表评论

电子邮件地址不会被公开。 必填项已用*标注