Live2D

python迭代

1. 并行迭代

有时候,你可能想同时迭代两个序列。假设有下面两个列表:

names = ['anne', 'beth', 'george', 'damon']
ages = [12, 45, 32, 102]

如果要打印名字和对应的年龄,可以像下面这样做:

for i in range(len(names)):
  print(names[i], 'is', ages[i], 'years old')

i 是用作循环索引的变量的标准名称。一个很有用的并行迭代工具是内置函数 zip ,它将两个序列“缝合”起来,并返回一个由元组组成的序列。返回值是一个适合迭代的对象,要查看其内
容,可使用 list 将其转换为列表。

>>> list(zip(names, ages))
[('anne', 12), ('beth', 45), ('george', 32), ('damon', 102)]

“缝合”后,可在循环中将元组解包。

for name, age in zip(names, ages):
  print(name, 'is', age, 'years old')

函数 zip 可用于“缝合”任意数量的序列。需要指出的是,当序列的长度不同时,函数 zip 将
在最短的序列用完后停止“缝合”。

>>> list(zip(range(5), range(100000000)))
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]

 2. 迭代时获取索引

在有些情况下,你需要在迭代对象序列的同时获取当前对象的索引。例如,你可能想替换一个字符串列表中所有包含子串 'xxx' 的字符串。当然,完成这种任务的方法有很多,但这里假设
你要像下面这样做:

index = 0
for string in strings:
    if 'xxx' in string:
        strings[index] = '[censored]'
    index += 1

 

这个解决方案虽然可以接受,但看起来也有点笨拙。另一种解决方案是使用内置函数enumerate 。这个函数让你能够迭代索引值对,其中的索引是自动提供的。

strings = ['abc','efd','xxx','ooo','btc']
for index, string in enumerate(strings):
    if 'xxx' in string:
        strings[index] = '[censored]'

 3. 反向迭代和排序后再迭代

来看另外两个很有用的函数: reversed 和 sorted 。它们类似于列表方法 reverse 和 sort ( sorted接受的参数也与 sort 类似),但可用于任何序列或可迭代的对象,且不就地修改对象,而是返回
反转和排序后的版本。

>>> sorted([4, 3, 6, 8, 3])
[3, 3, 4, 6, 8]
>>> sorted('Hello, world!')
[' ', '!', ',', 'H', 'd', 'e', 'l', 'l', 'l', 'o', 'o', 'r', 'w']
>>> list(reversed('Hello, world!'))
['!', 'd', 'l', 'r', 'o', 'w', ' ', ',', 'o', 'l', 'l', 'e', 'H']
>>> ''.join(reversed('Hello, world!'))
'!dlrow ,olleH'

  

请注意, sorted 返回一个列表,而 reversed 像 zip 那样返回一个更神秘的可迭代对象。你无需关心这到底意味着什么,只管在 for 循环或 join 等方法中使用它,不会有任何问题。只是你不能
对它执行索引或切片操作,也不能直接对它调用列表的方法。要执行这些操作,可先使用 list 对返回的对象进行转换。

要按字母表排序,可先转换为小写。为此,可将 sort 或 sorted 的 key 参数设置为 str.lower 。例如, sorted("aBc", key=str.lower) 返回 ['a', 'B', 'c'] 。

posted @ 2019-06-29 11:11  穆梓先生  阅读(295)  评论(0编辑  收藏  举报
$(function(){ $('#returnTop').click(function () { $('html,body').animate({ scrollTop: '0px' }, 800); returnfalse; }); });