Python:列表反序和解析

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)

 

2)列表解析法

实例:刷选出列表中大于10的数据

from random import randint
list_1 = [randint(0, 20) for i in range(30)]
list_2 = [x for x in list_1 if x >= 10]
print(list_2)

 

posted @ 2018-04-09 09:30  何永灿  阅读(2084)  评论(0编辑  收藏  举报