【问题标题】:How to use enumerate and slicing together如何一起使用枚举和切片
【发布时间】:2018-09-03 18:10:22
【问题描述】:

以下是我想要每 10 个项目的情况下 enumerate 的正常用法:

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

2 2
12 12
22 22
32 32
42 42

我该怎么做?

【问题讨论】:

    标签: python-3.x slice enumerate


    【解决方案1】:

    不知道你为什么这样做,但你可以在测试中从index 中减去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,如果n=0 是基本情况。

    或者,从枚举中的-n 开始,它会为您提供正确的值(但不同的索引):

    In []:
    n = 1
    for index, value in enumerate(range(50), -n):
        if index % 10 == 0:
            print(index,value)
    
    Out[]:
    0 1
    10 11
    20 21
    30 31
    40 41
    

    但你真的不需要enumerate% 索引来获取每10个值,假设你想处理任何可迭代的,只需使用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
    

    【讨论】:

      【解决方案2】:

      我会使用以下函数:

      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
      ...
      

      如果我是对的。

      【讨论】:

        猜你喜欢
        • 2014-06-03
        • 2015-12-17
        • 1970-01-01
        • 2018-04-22
        • 1970-01-01
        • 2023-03-10
        • 1970-01-01
        • 2010-10-25
        • 2019-02-16
        相关资源
        最近更新 更多