AdSense

網頁

2020/12/8

Python len() 取得物件長度

Python 的len(s)函式可取得物件的長度。

傳入的參數可以是序列(string, bytes, list, tuple)或集合(dictionary, set, frozen set)。如果是物件則會回傳實作__len__函式的回傳結果。

一些範例。

s = "hello world"  # string
print(len(s))  # 11

int_list = [1,2,3,4,5]  # list
print(len(int_list))  # 5

int_list = range(0, 10)
print(len(int_list))  # 9

b = b'hello world'  # bytes
print(len(b))  # 11

t = ("hello", "world")  # tuple
print(len(t))  # 2

int_set = {1, 2, 3}  # set
print(len(int_set))  # 3

dict_employee = {'name':'John', 'age':27}  # dictionary
print(len(dict_employee))  # 2


class Employee:
    
    def __init__(self, name, age):
        self.name = name  # instance variable
        self.age = age  # instance variable

    def __len__(self):
        return len(self.name) + self.age
        

employee = Employee('John', 27) # create Employee instance 'employee'
print(len(employee))  # 31 (4 + 27)


沒有留言:

AdSense