在Python中创建同时循环 [英] Creating Simultaneous Loops in Python
本文介绍了在Python中创建同时循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想创建一个具有这种感觉的循环:
I want to create a loop who has this sense:
for i in xrange(0,10):
for k in xrange(0,10):
z=k+i
print z
where the output should be
0
2
4
6
8
10
12
14
16
18
推荐答案
您可以使用>code> zip 将多个列表(或可迭代对象)变成成对的*元组:
You can use zip
to turn multiple lists (or iterables) into pairwise* tuples:
>>> for a,b in zip(xrange(10), xrange(10)):
... print a+b
...
0
2
4
6
8
10
12
14
16
18
但是 zip
在大集合上的缩放效果不如 izip
(上面提到过). zip
的优点是它是内置的,您不必导入itertools
-以及那个是否实际上是一个优势是主观的.
But zip
will not scale as well as izip
(that sth mentioned) on larger sets. zip
's advantage is that it is a built-in and you don't have to import itertools
-- and whether that is actually an advantage is subjective.
*不仅是成对的,而且是 n 的.元组的长度将与您传递给 zip
的可迭代对象的数量相同.
*Not just pairwise, but n-wise. The tuples' length will be the same as the number of iterables you pass in to zip
.
这篇关于在Python中创建同时循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文