王尹平 竹子照,365qingseluntan,受诅碾压者精华
08#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 进行定制排序
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
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.
strs = ['hello', 'and', 'goodbye'] shouting = [ s.upper() + '!!!' for s in strs ] ## ['hello!!!', 'and!!!', 'goodbye!!!']
## select values
##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
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.
读取unicode文件,可以使用 codecs 模块:
import codecs f = codecs.open('foo.txt', 'ru', 'utf-8') for line in f: # here line is a *unicode* string
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
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
Python 实现将numpy中的nan和inf,nan替换成对应的均值
python爬虫把url链接编码成gbk2312格式过程解析
网友评论