python基础---迭代工具

迭代是循环的另一种说法

并行迭代

>>> names = ['anne', 'beth', 'george', 'damon']
>>> ages = [12,45,32,102]
>>> for i in range(len(names)):
    print(names[i],'is', ages[i],'years old')


anne is 12 years old
beth is 45 years old
george is 32 years old
damon is 102 years old

#另一种方法:其中zip函数可以用于任意多的序列,将序列“压缩”在一起,然后返回一个元组列表
>>> for names,ages in zip(names, ages):
    print(names,'is',ages, 'years old')

按索引迭代

for index, string in enumerate(strings):   #其中enumerate(枚举,列举)函数可以在提供索引的地方返回迭代索引和值
    if 'xxx' in string:
        string[index] = '[censored]'

循环中的else语句

for i in range(99,81,-1):
    root = sqrt(i)
    if root == int(root):
        print(i)
        break
else:
    print("don't")


don't

如上代码可以看到,循环for/while是可以使用else语句的,即循环完成后将会继续执行else语句中的内容

列表推导式—-轻量级循环

利用其它列表创建新列表的方法

>>> [x*x for x in range(10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> [x*x for x in range(10) if x % 3 == 0]
[0, 9, 36, 81]
>>> [(x,y) for x in range(3) for y in range(3)]
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]

#得到首字母相同的男孩女孩
>>> girls = ['alice', 'bernice', 'clarice']
>>> boys = ['chris', 'arnold', 'bob']
>>> [b+'+'+g for b in girls for g in boys if b[0]==g[0]]
['alice+arnold', 'bernice+bob', 'clarice+chris']
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值