Python 3.x 如何同时使用枚举和切片
以下是enumerate在我希望每10项中包含一项的情况下的正常用法:Python 3.x 如何同时使用枚举和切片,python-3.x,slice,enumerate,Python 3.x,Slice,Enumerate,以下是enumerate在我希望每10项中包含一项的情况下的正常用法: for index, value in enumerate(range(50)): if index % 10 == 0: print(index,value) 输出: 0 0 10 10 20 20 30 30 40 40 现在,假设我希望输出为: 1 1 11 11 21 21 31 31 41 41 或 我该怎么做呢?不知道你为什么这样做,但你可以在测试中从索引中减去n,例如: In []
for index, value in enumerate(range(50)):
if index % 10 == 0:
print(index,value)
输出:
0 0
10 10
20 20
30 30
40 40
现在,假设我希望输出为:
1 1
11 11
21 21
31 31
41 41
或
我该怎么做呢?不知道你为什么这样做,但你可以在测试中从
索引中减去n
,例如:
In []:
n = 1
for index, value in enumerate(range(50)):
if (index-n) % 10 == 0:
print(index,value)
Out[]:
1 1
11 11
21 21
31 31
41 41
只需为第二种情况设置n=2
,如果coursen=0
是基本情况
或者,只需从enumerate中的-n
开始,这将为您提供正确的值(但不同的索引):
但是,如果您想处理任何iterable,那么您确实不需要枚举
和%
索引,只需使用itertools.islice()
,例如
In []:
import itertools as it
n = 0
for value in it.islice(range(50), n, None, 10):
print(value)
Out[]:
0
10
20
30
40
然后只需更改n
的值,例如:
In []:
n = 1
for value in it.islice(range(50), n, None, 10):
print(value)
Out[]:
1
11
21
31
41
我将使用以下功能:
def somefunc(n):
for i in list(range(50))[n::10]:
yield i, i
然后使用所需的整数调用函数:
for i, j in somefunc(2):
print(i, j)
例如,您是否应该返回
2, 2
12, 12
22, 22
...
如果我是对的
for i, j in somefunc(2):
print(i, j)
2, 2
12, 12
22, 22
...