Some iteration utilities

本文介绍了Python中几种实用的迭代技巧,包括并行迭代、编号迭代、反转及排序迭代等。通过内置函数如zip、enumerate、reversed和sorted,可以更高效地处理序列数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Python has several functions that can be useful when iterating over a sequence (or other iterable object). Some of these are available in the itertools module , but there are some built-in functions that come in quite handy as well.
1)parallel iteration
Sometimes you want to iterate over two sequences at the same time.A useful tool for parallel iteration is the built-in function zip, which “zips” together the sequences, returning a list of tuples:
names = ['anne', 'beth', 'george', 'damon']
ages = [12, 45, 32, 102]
>>> zip(names, ages)
[('anne', 12), ('beth', 45), ('george', 32), ('damon', 102)]
2)numbered iteration
In some cases, you want to iterate over a sequence of objects and at the same time have access to the index of the current object:
index = 0
for string in strings:
      if 'xxx' in string:
         strings[index] = '[censored]'
      index += 1
This also seems a bit awkward, although acceptable. Another solution is to use the built-in function enumerate:
for index, string in enumerate(strings):
      if 'xxx' in string:
            strings[index] = '[censored]'
This function lets you iterate over index-value pairs, where the indices are supplied automatically.
3)reversed and sorted iteration
Let's look at another couple of useful functions: reversed and sorted. They're similar to the list methods reverse and sort (with sorted taking arguments similar to those taken by sort), but they work on any sequence or iterable object, and instead of modifying the object in place, they return reversed and sorted versions:
>>> sorted([4, 3, 6, 8, 3])
[3, 3, 4, 6, 8]
>>> sorted('Hello, world!')
[' ', '!', ',', 'H', 'd', 'e', 'l', 'l', 'l', 'o', 'o', 'r', 'w']
>>> reversed('Hello, world!')
<reversed object at 0xb7289fcc>
>>> list(reversed('Hello, world!'))
['!', 'd', 'l', 'r', 'o', 'w', ' ', ',', 'o', 'l', 'l', 'e', 'H']
>>> ''.join(reversed('Hello, world!'))
'!dlrow ,olleH'
Note that although sorted returns a list, reversed returns a more mysterious iterable object. You don't need to worry about what this really means; you can use it in for loops or methods such as join without any problems. You just can't index or slice it, or call list methods on it directly. In order to perform those tasks, you need to convert the returned object, using the list type, as shown in the previous example.





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值