Google Python Class --- Dict and File

Dict Hash Table


  • 在Python中Key/Value結構的哈希表叫作Dict[字典]python

  • 字典使用{}定義,內容是一系列的Key:Value。空的字典用{}表示函數

  • 字符串、數字、元組均可以做爲字典的key.ui

## Can build up a dict by starting with the the empty dict {}
      ## and storing key/value pairs into the dict like this:
      ## dict[key] = value-for-that-key
      dict = {}   #建立空字典
      dict['a'] = 'alpha'  # 使用dict[key] = value的方式對字典賦值
      dict['g'] = 'gamma'
      dict['o'] = 'omega'
    
      print dict  ## {'a': 'alpha', 'o': 'omega', 'g': 'gamma'}
    
      print dict['a']     ## 返回 'alpha'
      dict['a'] = 6       ## 對 dict['a'] 賦值
      'a' in dict         ## True
      ## print dict['z']                  ## 找不到對應的key,會拋出異常
      if 'z' in dict: print dict['z']     ## 
      print dict.get('z')  ## None (instead of KeyError)

clipboard.png

  • 可使用for循環打印字典的keythis

# 方法一
      for key in dict: print key
      ## prints a g o
  • 可使用dict.keys() 和 dict.values()得到字典的key和valuespa

##dict.keys()
  ## Exactly the same as above
  for key in dict.keys(): print key

  ##打印dict.keys()返回的列表:
  print dict.keys()  ## ['a', 'o', 'g']

  ## 返回字典中value組成的列表
  print dict.values()  ## ['alpha', 'omega', 'gamma']

  ## 能夠對key進行排序,並打印對應的key和value
  for key in sorted(dict.keys()):
    print key, dict[key]
  • dict.item()方法能夠返回由(key,value)組成的元組code

print dict.items()  ##  [('a', 'alpha'), ('o', 'omega'), ('g', 'gamma')]
    
      ## 循環打印key和value
      for k, v in dict.items(): print k, '>', v
      ## a > alpha    o > omega     g > gamma

Dict Formatting


  • % 操做符一樣適用於字典orm

hash = {}
      hash['word'] = 'garfield'
      hash['count'] = 42
      s = 'I want %(count)d copies of %(word)s' % hash  # %d for int, %s for string
      # 'I want 42 copies of garfield'

Del


  • "Del"操做符用來刪除一個變量的定義。"Del"操做符可以做用於list元素或者切片blog

var = 6
      del var  # 刪除變量var
      
      list = ['a', 'b', 'c', 'd']
      del list[0]     ## 刪除列表中的第一個元素
      del list[-2:]   ## 刪除列表最後兩個元素
      print list      ## ['b']
    
      dict = {'a':1, 'b':2, 'c':3}
      del dict['b']   ## 刪除key=b的字典條目
      print dict      ## {'a':1, 'c':3}

Files


  • Open()函數返回一個文件的句柄,一般用來讀取或者寫入一個文件排序

# Echo the contents of a file
      f = open('foo.txt', 'rU')
      for line in f:   ## iterates over the lines of the file
        print line,    ## trailing , so print does not add an end-of-line char
                       ## since 'line' already includes the end-of line.
      f.close()
  • f.readlines()方法會將整個文件放入內存,返回以每行爲元素的列表進程

f.readlines()
    ['Hello,時隔一個多月,終於再次回到博客啦,首先跟你們說聲抱歉,許多評論沒有及時回覆感到很是抱歉,但願我如今給你們的回覆爲時不晚。\n',
     '\n',
     '距離上次在博客上寫日記過去了幾個月了吧。那時的我剛剛結束大學三年級。而如今,大四上半學期已通過半啦。這半年的時間能夠說忙也能夠說不忙。不忙是說這半年以來的課程比較輕鬆,只有四門選修課,學業負擔比較輕。忙是說半年以來各類錯綜複雜的事情,許多事情須要好好安排一下時間才能夠好好把握各個「進程」的合理分配。\n',
     '\n',
     '那麼就從我上第二天記開始總結一下吧。']
  • read()方法會讀取整個文件,並把文件內容放到一個字符串中

f = open('liwei.txt')
    f.read()
    'Hello,時隔一個多月,終於再次回到博客啦,首先跟你們說聲抱歉,許多評論沒有及時回覆感到很是抱歉,但願我如今給你們的回覆爲時不晚。\n\n距離上次在博客上寫日記過去了幾個月了吧。那時的我剛剛結束大學三年級。而如今,大四上半學期已通過半啦。這半年的時間能夠說忙也能夠說不忙。不忙是說這半年以來的課程比較輕鬆,只有四門選修課,學業負擔比較輕。忙是說半年以來各類錯綜複雜的事情,許多事情須要好好安排一下時間才能夠好好把握各個「進程」的合理分配。\n\n那麼就從我上第二天記開始總結一下吧。'
  • f.write()方法能夠將內容寫入文件中。除此以外,在Python3中,可使用 print(string,file=f)來寫入

相關文章
相關標籤/搜索