编程语言
首页 > 编程语言> > Python 推导,内含,迭代器

Python 推导,内含,迭代器

作者:互联网

Python语法–推导或内含

  1. 典型的情况:
for i in aiterator
  1. 利用推导获取一个平方数列表
square = [i * i for i in range(1, 11)]
for i in range(1, 11):
    square.append(i * i)
  1. 字典推导语法如下格式:
{key_exp:value_exp for key_exp,value_exp in aiterator}
keys = ['name', 'age', 'weight']
values = ['jiamin', '28', '81']
infoMap = {k: v for k, v in zip(keys, values)}
推导+逻辑处理
  1. 使用if语句实现选择处理遍历的元素,如下语法规则:
for i in aiterator if ...
{key_exp:value_exp for key_exp,value_exp in aiterator if ...}
##取偶数
square_odd = [i * i for i in range(1, 11) if i * i % 2 == 0]
##只取年龄
infoMap_odd = {k: v for k, v in zip(keys, values) if k == 'age'}
##通过字典生成字典
dict_one = {'name': 'jiamin', 'age': '28', 'weight': '81'}
dict_two = {k: v for k, v in dict_one.items() if k == 'name'}

python中迭代器

自定义迭代器
__iter__() ## 方法放回对象本身,他是for语句使用迭代器的要求
__next__() ## 方法返回容器中下一个元素或数据,当容器中数据用完,应该引发StopIteration
## 自定义代器遍历
class MyIterator:
    def __init__(self, x=2, xmax=100):
        self.__mul, self.__x = x, x
        self.__xmax = xmax

    def __iter__(self):
        return self

    def __next__(self):
        if self.__x and self.__x != 1:
            self.__mul *= self.__x
            if self.__mul <= self.__xmax:
                return self.__mul
            else:
                raise StopIteration
        else:
            raise StopIteration
if __name__ == '__main__':
    myiter = MyIterator()
    for i in myiter:
        print('自定义迭代器: ', i)
内置迭代器工具
## 内建迭代器遍历
class Counter:
    def __init__(self, x=0):
        self.x = x


counter = Counter()


def used_iter():
    counter.x += 2
    return counter.x


for i in iter(used_iter, 8):
    print("内建迭代器遍历: ", i)

itertools模块中常用工具函数
import itertools


## 迭代器工具类
## 从1 开始,每此以3 为步迭代
def countTest():
    for i in itertools.count(1, 3):
        print(i)
        if i >= 10:
            break


##无线循环迭代
def cycleTest():
    for i in itertools.cycle([1, 2, 3]):
        print(i)


## 循环迭代  输出: [2, 2, 2]
def repeatTest():
    print(list(itertools.repeat(2, 3)))


##chain(p,q,...)链接迭代,将p,q连接起来迭代输出:[1, 2, 3, 4, 5, 6]
def chainTest():
    print(list(itertools.chain([1, 2, 3], [4, 5, 6])))


## compress(data,selectors) 根据selectors中的值选择迭代data序列中的值 输出: [1, 3]
def compressTest():
    print(list(itertools.compress([1, 2, 3, 4], [1, None, True, False])))


## dropwhile(pred,seq) 当pred对序列元素处理结果为False时候开始迭代seq后所有的值 输出:[1, 2, 10, 11]
def dropwhileTest():
    print(list(itertools.dropwhile(lambda x: x > 6, [8, 9, 1, 2, 10, 11])))


## filterfalse(pred,seq) 当pred处理为假的元素 输出:[1, 2]
def filterfalseTest():
    print(list(itertools.filterfalse(lambda x: x > 6, [8, 9, 1, 2, 10, 11])))


## takewhile 与dropwhile相反  当pred对序列元素处理结果为True时候开始迭代seq后所有的值 输出:[8, 9]
def takewhileTest():
    print(list(itertools.takewhile(lambda x: x > 6, [8, 9, 1, 2, 10, 11])))


## tee(it, n) 将it重复n次进行迭代
def teeTest():
    for its in itertools.tee([0, 1], 2):
        for it in its:
            print(it)


## zip_longest(p,q,...) 按每个序列中对应位置元素组合成新的元素进行迭代
def zip_longestTest():
    for i in itertools.zip_longest([1, 2, 3, 8], [3, 4, 5, 76], (0, 2, 3, 4)):
        print(i)


## product(p,q,...[,n]) 迭代排列中出现元素的全排列
def productTest():
    for i in itertools.product([1, 2, 3, 8], [3, 4, 5, 76]):
        print(i)


## permutations(p, q) 求p迭代序列中q个元素的全排列
def permutationsTest():
    print(list(itertools.permutations([1, 2, 3, 4], 4)))
    print(list(itertools.permutations('ASBD', 4)))


## combinations(p, r)迭代序列中r个元素的组合
def combinationsTest():
    print(list(itertools.combinations('abc', 2)))
    print(list(itertools.combinations([1, 2, 3], 2)))


if __name__ == '__main__':
    combinationsTest()

标签:__,迭代,推导,Python,##,itertools,print,def
来源: https://blog.csdn.net/liaojiamin0102/article/details/122429336