【问题标题】:Iterate through small list n times遍历小列表 n 次
【发布时间】:2020-12-28 05:17:33
【问题描述】:

我有什么:

   list_1 = ["a", "b", "c"]
   rounds = 5

我需要的是:一次获取一个小列表的元素,n 次;考虑到列表的长度小于n

   for _ in range(rounds):
      -> get element of list_1 sequentially

预期结果:

   "a"
   "b"
   "c"
   "a"
   "b"

obs:numpy 方法是可以接受的。

谢谢

【问题讨论】:

标签: python list numpy loops


【解决方案1】:

itertools.cycle迭代器中获取任意数量的值:

import itertools
list_1 = ["a", "b", "c"]
rounds = 5
i = itertools.cycle(list_1)
print([next(i) for _ in range(rounds)])

给予

['a', 'b', 'c', 'a', 'b']

当然,您不必构建列表 - 这是一个for 循环(使用上面的迭代器):

for _ in range(rounds):
    print(next(i))

【讨论】:

    【解决方案2】:

    您可以仅基于 Numpy 函数来完成您的任务, 没有来自例如的支持itertools.

    将循环运行为:

    for tt in np.resize(list_1, rounds):
        print(tt)
    

    或者,如果您需要一次性完成整个列表,请运行:

    result = np.resize(list_1, rounds)
    

    【讨论】:

      【解决方案3】:

      您不需要为此使用任何 Python 模块,只需在传递最后一个元素后使用模 % 运算符返回第一个元素:

      list_1 = ["a", "b", "c"]
      rounds = 5
      
      for i in range(rounds):
          print(list_1[i % len(list_1)])
      

      结果:

      a
      b
      c
      a
      b
      

      您还可以将len(list_1) 分配给变量,例如length,这样您就不必在每次迭代中计算长度。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-02-10
        • 1970-01-01
        • 1970-01-01
        • 2010-12-18
        • 2022-01-07
        相关资源
        最近更新 更多