python 快速入门

发布时间:2019-06-30 16:51:51编辑:auto阅读(1924)

     

      

    导入

    #from dir1 import test

    #import dir1.test as test

    列表推到:

    b3 =[x for x in xing if x in ming]
    print(b3)

     li = [1, 2, 3, 4]
    [elem*2 for elem in li] 

    print [x*y for x in [1,2,3] for y in  [1,2,3]]



    zip:

    l1=[1,2,3,4]
    l2=[2,4,6,7]
    print(zip(l1,l2))
    for (a,b)in zip(l1,l2):
        print((a,b))

    enumerate:

    testStr = 'cainiao'
    for (offset,item) in enumerate(testStr):
      print (item,'appears at offset:',offset)



    has_key was removed from python3.x and use (key in dict)

    http://blog.csdn.net/dingyaguang117/article/details/7170881

    http://www.cainiao8.com/python/basic/python_11_for.html


    循环组合

    while i<len(xing):
        print ([xing[i]+ming[i]])
        i=i+1

    xing=['wang','li','zhang',"liu"]
    for i in range(len(xing)):
         print (i, xing[i])

    for i in range(1, 5):
        print i
    else:
        print 'The for loop is over'

    while True:
        s = raw_input('Enter something : ')
        if s == 'quit':
            break
        if len(s) < 3:
            continue
        print 'Input is of sufficient length'

    快速生成词典

    ---------

    list1 =['a','b','c','d']
    d = {}
    list2=[24, 53, 26, 9]
    i=0
    while i <len(list1) :
        d[list1[i]]=list2[i]
        i=i+1
    print(d)

    list1 =['a','b','c','d']
    d = {'a':24, 'b':53 ,'c':26, 'd':9}
    new_list = [d[k] for k in list1]
    assert new_list == [24, 53, 26, 9]

    定位字符的位置

    ------------------

    def read_line(line):
        sample = {}
        n = len(line)
        for i in range(n):
          if line[i]!='0':
            sample[i] = int(line[i])
            '''sample[i] is key  int(line[i]) means make it int type'''
            print(sample)
        return sample
      
    print(read_line('01101001'))

    字符个数统计

    d={}
    x_string='Pythonhello'
    for x in x_string:
        key=x.rstrip()
        if key in d:
            d[key]=d[key]+1
        else:
            d[key] = 1

    for k,v in d.items():
        print("%s=%s"%(k,v))

    http://www.cainiao8.com/python/basic/python_07_dictionary_tuple.html

    ------------------------------------

    导入

    '''import hello
    name_pr(q,b,c)
    a=hello.name_pr(2,3,4)
    print(a)''


    引用计算单词数目

    1. import sys  

    2. import string  

    3. #import collections  

    4.   

    5. if len(sys.argv) == 1 or sys.argv[1] in {"-h", "--help"}:  

    6.  print("usage: uniqueword filename_1 filename_2 ... filename_n")  

    7.  sys.exit()  

    8. else:  

    9.  words = {}   

    10.  # words = collections.defaultdict(int)  

    11.  strip = string.whitespace + string.punctuation + string.digits + "\"'"  

    12.  for filename in sys.argv[1:]:  

    13.   for line in open(filename):  

    14.    for word in line.split():  

    15.     word = word.strip(strip)  

    16.     if len(word) >= 2:  

    17.      words[word] = words.get(word, 0) + 1  

    18.      # words[word] += 1  

    19.  for word in sorted(words):  

    20.   print("'{0}' occurs {1} times".format(word,words[word])) 
      可以使用get()方法来访问字典项,get()方法还可以设置第二个参数,如果b不存在,可以将第二个参数做为默认值返回。

    高级函数

    http://www.cainiao8.com/python/basic/python_13_function_adv.html

    迭代器

    #iterator
    testDict = {'name':'Chen  Zhe','gender':'male'}
    testIter = iter(testDict)
    print testIter.next()


    异常处理

    http://www.cainiao8.com/python/basic/python_16_exception.html




    字典(dict)转为字符串(string)

    我们可以比较容易的将字典(dict)类型转为字符串(string)类型。

    通过遍历dict中的所有元素就可以实现字典到字符串的转换:

    for key, value in sample_dic.items():
        print "\"%s\":\"%s\"" % (key, value)

     

    字符串(string)转为字典(dict)

    如何将一个字符串(string)转为字典(dict)呢?

    其实也很简单,只要用 eval()或exec() 函数就可以实现了。

    >>> a = "{'a': 'hi', 'b': 'there'}"
    >>> b = eval(a)
    >>> b
    {'a': 'hi', 'b': 'there'}
    >>> exec ("c=" + a)
    >>> c
    {'a': 'hi', 'b': 'there'}
    >>> 

     

    http://www.pythonclub.org/python-hacks/start

     

关键字