1. 程式人生 > >Python:列表list

Python:列表list

正向 class strong step 自動調用 使用 list 可用 ini

1)列表反序

A、list.reverse():將列表反序;

l = [1, 2, 3, 4, 5]

print(l.reverse())

-->[5, 4, 3, 2, 1]

B、l.[::-1] --> [5, 4, 3, 2, 1]

# l.[:-1] --> [1, 2, 3, 4]

C、reversed(list) :得到list的反向叠代器;

可用:for x in reversed(list):來反向叠代list;

# 執行reversed(list)時,需要調用__reversed__()方法,即反向叠代接口;

# liter(list):得到list的正向叠代器;

class FloatRange:
    def __init__(self, start, end, step = 0.1):
        self.start = start
        self.end = end
        self.step = step

    def __reversed__(self):
        t = self.end
        while t >= self.start:
            yield t
            t -= self.step

    def __iter__(self):
        t 
= self.start while t <= self.end: yield t t += self.step # 此循環,實例化時自動調用__iter__()方法,而不是__reversed__()方法; for x in FloatRange(1.0, 3.0, 0.5): print(x) # 此循環,只有定義了__reversed__()方法後,才能直接使用reversed; for x in reversed(FloatRange(1.0, 4.0, 0.5)): print(x)

Python:列表list