標籤:python sample 原因 sequence hit items pytho cond --
1、roundround(x,n)方法返回 x 的小數點四捨五入到n個數字 2、random實現隨機播放不重複的元素利用Python中的randomw.sample()函數實現resultList=random.sample(range(x,y); # sample(x,y)函數的作用是從序列x中,隨機播放y個不重複的元素。 3、%d 是整形萬用字元,%s是字串萬用字元print "一周有%d分鐘" %minitesprint "一周有%s秒"%str(seconds) 4、TypeError: ‘module‘ object is not callable原因分析:Python匯入模組的方法有兩種:import module 和 from module import,區別是前者所有匯入的東西使用時需加上模組名的限定,而後者不要。正確的代碼:>>> import Person>>> person = Person.Person(‘dnawo‘,‘man‘)>>> print person.Name或>>> from Person import *>>> person = Person(‘dnawo‘,‘man‘)>>> print person.Name 5、使用map將list中的str轉化成int文法map() 函數文法:map(function, iterable, ...)參數● function -- 函數,有兩個參數● iterable -- 一個或多個序列樣本map(str,[1,2,3.2,4,5])#將list中的str轉換成int、floatdata = [‘1‘,‘3.2‘,‘2‘]data = map(eval, data)print data #將list中的int\float轉換成str#方法一array=[1,2,3.2,4,5]new_array=map(str,array)print new_array#方法二array1=[1,2,3,4,5]new_array1=[str(x) for x in array1]print new_array1 6、使用x for x in 運算式#擷取1301到1500中間的200個數字,並用","隔開a=[index for index in range(1301,1501)]str= str(a)print str.replace("[","").replace("]","").replace(", ",",") 7、reduce用作累計運算reduce(...)reduce(function, sequence[, initial]) -> value樣本def multiply(a,b):return a*bprint reduce(multiply,(1,2,3,4)) 8、filter 用作過濾序列filter(...)filter(function or None, sequence) -> list, tuple, or string樣本#方法一def is_odd(x):return x%2==1print filter(is_odd,(1,2,3,4,5,6))#方法二print filter((lambda x:x%2==1),(1,2,3,4,5,6)) 9、sorted 用作排序,reverse=False正序,reverse=True逆序排列sorted(...)sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list樣本print sorted(["zara","asb","hm"],reverse=True) #將嵌套列表排序L = [(‘Bob‘, 75), (‘Adam‘, 92), (‘Bart‘, 66), (‘Lisa‘, 88)]new_dict=dict(L)b=sorted(new_dict.items(),key=lambda x: x[0],reverse=False) #按姓名正序排列c=sorted(new_dict.items(),key=lambda x: x[1],reverse=True) #按數字逆序排列
python文法積累(持續更新)