python語法積累(持續更新)
阿新 • • 發佈:2017-12-24
多個 嵌套 lac 返回 iterable ... mod bob spa 1、round
round(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分鐘" %minites
print "一周有%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、float
data = [‘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*b
print 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==1
print 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語法積累(持續更新)