python:內建方法

來源:互聯網
上載者:User

標籤:hex   zip   res   全域   十進位   sci   callable   處理   進位轉化   

#!usr/bin/env python
# -*- coding:utf-8 -*-

__author__ = "Samson"
s = -1
print(abs(s))#取絕對值
print(all([0,-1,3]))#傳入參數是否全部為真
print(any([0,-1,3]))#傳入參數有一個為真即為真
print(type(ascii([1,2,"qiong"])))#把一個資料對象轉化為可列印的字串
print(bin(20))#十進位轉化為二進位
print(bool([]))#判斷真假,空為假

a = bytes("abcde",encoding="utf-8")
b = bytearray("abcde",encoding="utf-8")#將參數變成位元組的形式
b[1] = 100
print(a.capitalize(),a)
print(b)

def sayhi():pass
print(callable(sayhi))#判斷是否可調用的

print(chr(100))#將數字轉換為對應的ascii碼
print(ord("A"))#將ascii碼轉換為對應的數字

code = "for i in range(10):print(i)"
exec(code)#將傳入的字串作為代碼執行

a = {}
print(dir(a))#查看對象可以調用哪些方法
print(divmod(5,2))#返回兩參數相除的商和餘數

#eval()函數可以使list,tuple,dict與string相互轉化。
a = "[[1,2], [3,4], [5,6], [7,8], [9,0]]"
b = "{1: ‘a‘, 2: ‘b‘}"
c = "([1,2], [3,4], [5,6], [7,8], (9,0))"
s = eval(a)#字串轉換成列表
t = eval(b)#字串轉換成字典
v = eval(c)#字串轉換成元組

res = filter(lambda n:n>5,range(10))#過濾
res = map(lambda n:n**2,range(10))#對傳入的值按參數1的方式處理相當於res = [lambda i:i**2 for i in range(10)]
import functools
res = functools.reduce(lambda x,y:x+y,range(10))#結果為45
print(res)

a = frozenset([1,4,333,212,333])#將列表修改為不可變的
print(globals())#將當前檔案中所有全域變數作為字典返回
print(locals())#返回當前檔案中所有局部變數
print(hex(120))#轉化為16進位
print(oct(120))#轉化為8進位
print(pow(3,4))#3的4次方
print(round(3.1415926,3))#保留3位小數點

#用sorted對字典排序
a = {6:2,8:0,1:4,-5:6,99:11,4:22}
print(sorted(a.items()))#對字典中key進行排序
print(sorted(a.items(),key=lambda x:x[1]))#對字典value進行排序
a = [1,2,3,4]
b = ["a","b","c","d","e"]
for i in zip(a,b):
print(i)
__import__("code")#調用code.py中的代碼並執行

python:內建方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.