现在的位置: 首页 > 综合 > 正文

Python快速入门(4)排序、字典、文件

2014年08月16日 ⁄ 综合 ⁄ 共 5671字 ⁄ 字号 评论关闭

08 
Python Sorting:
1.最简单的排序方式:

			#sorted(list) function: which takes a list and returns a new list with those elements in sorted order
			a = [5, 1, 4, 3]
			print sorted(a)  ## [1, 3, 4, 5]
			print a  ## [5, 1, 4, 3]
			
			#The sorted() function can be customized though optional arguments. The sorted() optional argument reverse=True, e.g. sorted(list, reverse=True), makes it sort backwards.
			strs = ['aa', 'BB', 'zz', 'CC']
			print sorted(strs)  ## ['BB', 'CC', 'aa', 'zz'] (case sensitive)
			print sorted(strs, reverse=True)   ## ['zz', 'aa', 'CC', 'BB']

2. 使用key=func 进行定制排序
#1.For example with a list of strings, specifying key=len (the built in len() function) sorts the strings by length, from shortest to longest. The sort calls len() for each string to get the list of proxy length values,
and the sorts with those proxy values.

			strs = ['ccc', 'aaaa', 'd', 'bb']
			print sorted(strs, key=len)  ## ['d', 'bb', 'ccc', 'aaaa']
			
			#2.As another example, specifying "str.lower" as the key function is a way to force the sorting to treat uppercase and lowercase the same:
			
			## "key" argument specifying str.lower function to use for sorting
			print sorted(strs, key=str.lower)  ## ['aa', 'BB', 'CC', 'zz']
			
			#3.You can also pass in your own MyFn as the key function, like this:
			
			## Say we have a list of strings we want to sort by the last letter of the string.
		    strs = ['xc', 'zb', 'yd' ,'wa']

		    ## Write a little function that takes a string, and returns its last letter.
		    ## This will be the key function (takes in 1 value, returns 1 value).
		    def MyFn(s):
			  return s[-1]

		    ## Now pass key=MyFn to sorted() to sort by the last letter:
		    print sorted(strs, key=MyFn)  ## ['wa', 'zb', 'xc', 'yd']

3. sort()方法

			#the sort() method on a list sorts that list into ascending order
			list.sort()
			#the sort() method changes the underlying list and returns None

元组tuple
tuple是不可变的,并且大小不能改变
##Tuples play a sort of "struct" role in Python -- a convenient way to pass around a little logical, fixed size bundle of values. 

		  tuple = (1, 2, 'hi')
		  print len(tuple)  ## 3
		  print tuple[2]    ## hi
		  tuple[2] = 'bye'  ## NO, tuples cannot be changed
		  tuple = (1, 2, 'bye')  ## this works, it created a new tuple

列表进阶:
1.

		  nums = [1, 2, 3, 4]
		  squares = [ n * n for n in nums ]   ## [1, 4, 9, 16]
		  
		[ expr for var in nums] -- ## the expr to its left is evaluated once for each element to give the values for the new list.

2.

		  strs = ['hello', 'and', 'goodbye']

		  shouting = [ s.upper() + '!!!' for s in strs ]
		  ## ['HELLO!!!', 'AND!!!', 'GOODBYE!!!']

3. 也可以加入if判断语句:

		  ## Select values <= 2
		  nums = [2, 8, 1, 6]
		  small = [ n for n in nums if n <= 2 ]  ## [2, 1]

		  ## Select fruits containing 'a', change to upper case
		  fruits = ['apple', 'cherry', 'bannana', 'lemon']
		  afruits = [ s.upper() for s in fruits if 'a' in s ]
		  ## ['APPLE', 'BANNANA']

字典dict:{}
<key,value>   映射类型/哈希表

##The contents of a dict can be written as a series of key:value pairs within braces { }, e.g. dict = {key1:value1, key2:value2, ... }. The "empty dict" is just an empty pair of curly braces
{}.

字典是python中唯一的映射类型(哈希表),常用成员方法:
keys()
values()
items()

		dic = {"name":"well","age":20,"gender":"male"}
		dic.keys() #返回所有的key
		
		dic['name']  #返回 "well"
		  ## 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['g'] = 'gamma'
		  dict['o'] = 'omega'

		  print dict  ## {'a': 'alpha', 'o': 'omega', 'g': 'gamma'}

		  print dict['a']     ## Simple lookup, returns 'alpha'
		  dict['a'] = 6       ## Put new key/value into dict
		  'a' in dict         ## True
		  ## print dict['z']                  ## Throws KeyError
		  if 'z' in dict: print dict['z']     ## Avoid KeyError
		  print dict.get('z')  ## None (instead of KeyError)
		  
		  
		  ## By default, iterating over a dict iterates over its keys.
		  ## Note that the keys are in a random order.
		  for key in dict: print key
		  ## prints a g o
		  
		  ## Exactly the same as above
		  for key in dict.keys(): print key

		  ## Get the .keys() list:
		  print dict.keys()  ## ['a', 'o', 'g']

		  ## Likewise, there's a .values() list of values
		  print dict.values()  ## ['alpha', 'omega', 'gamma']

		  ## Common case -- loop over the keys in sorted order,
		  ## accessing each key/value
		  for key in sorted(dict.keys()):
			print key, dict[key]
		  
		  ## .items() is the dict expressed as (key, value) tuples
		  print dict.items()  ##  [('a', 'alpha'), ('o', 'omega'), ('g', 'gamma')]

		  ## This loop syntax accesses the whole dict by looping
		  ## over the .items() tuple list, accessing one (key, value)
		  ## pair on each iteration.
		  for k, v in dict.items(): print k, '>', v
		  ## a > alpha    o > omega     g > gamma

      字典与格式化:
      ##The % operator works conveniently to substitute values from a dict into a string by name:

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

Del:
##The "del" operator does deletions. In the simplest case, it can remove the definition of a variable, as if that variable had not been defined. Del can also be used on list elements or slices to delete that part of the
list and to delete entries from a dictionary.

		  var = 6
		  del var  # var no more!
		  
		  list = ['a', 'b', 'c', 'd']
		  del list[0]     ## Delete first element
		  del list[-2:]   ## Delete last two elements
		  print list      ## ['b']

		  dict = {'a':1, 'b':2, 'c':3}
		  del dict['b']   ## Delete 'b' entry
		  print dict      ## {'a':1, 'c':3}

     文件:

		  # Echo the contents of a file
		  f = open('foo.txt', 'rU')
		  ## The special mode 'rU' is the "Universal" option for text files where it's smart about converting different line-endings so they always come through as a simple '\n'. 
		  ## Instead of 'r', use 'w' for writing, and 'a' for append.
		  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()

 ## The f.readlines() method reads the whole file into memory and returns its contents as a list of its lines. 
 ## The f.read() method reads the whole file into a single string, which can be a handy way to deal with the text all at once, such as with regular expressions we'll see later.
 ## For writing, f.write(string) method is the easiest way to write data to an open output file.


 读取unicode文件,可以使用 codecs 模块:

		    import codecs

			f = codecs.open('foo.txt', 'rU', 'utf-8')
			for line in f:
			  # here line is a *unicode* string

Ex.统计文件中的各个单词的个数:
  显示格式为:

  word1 count1
  word2 count2
  ......

		def word_count_dict(filename):
		  """Returns a word/count dict for this filename."""
		  # Utility used by count() and Topcount().
		  word_count = {}  # Map each word to its count
		  input_file = open(filename, 'r')
		  for line in input_file:
			words = line.split()
			for word in words:
			  word = word.lower()
			  # Special case if we're seeing this word for the first time.
			  if not word in word_count:
				word_count[word] = 1
			  else:
				word_count[word] = word_count[word] + 1
		  input_file.close()  # Not strictly required, but good form.
		  return word_count

抱歉!评论已关闭.