python - 循环显示python列表中的项目分组列表

标签 python arrays list

我有一个数组,给定组中的项目数和组数,我需要循环循环打印数组。
数组-[1,2,3,4,5,6]
4组
迭代次数-7
输出应为:

['1', '2', '3', '4']
['5', '6', '1', '2']
['3', '4', '5', '6']
['1', '2', '3', '4']
['5', '6', '1', '2']
['3', '4', '5', '6']
['1', '2', '3', '4']

最佳答案

一种解决方案是将itertools.cycleitertools.slice结合在一起。

from itertools import cycle, islice

def format_print(iterable, group_size, iterations):
    iterable = cycle(iterable)
    for _ in range(iterations):
        print(list(islice(iterable, 0, group_size)))

format_print(range(1, 7), 4, 7)
输出:
[1, 2, 3, 4]
[5, 6, 1, 2]
[3, 4, 5, 6]
[1, 2, 3, 4]
[5, 6, 1, 2]
[3, 4, 5, 6]
[1, 2, 3, 4]
如果需要打印字符串列表,可以将cycle(iterable)替换为cycle(map(str, iterable))

关于python - 循环显示python列表中的项目分组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63201014/

相关文章:

python - Python 中的 OpenCV mat::convertTo

python - PySpark:从另一个 Notebook 导入变量时,如何抑制 PySpark 单元中的 %run 输出?

python - Django 中的异步文件写入功能是否需要 Celery?

php - 根据最小值和最大值消除数组元素

java - 如何存储和更改二维列表的值?

PHP 在连字符数组中查找缺失的数字

c# - 在函数参数中使用多个谓词?

python - 如何使用 minidom 读取具有属性的 XML 标签的值

android - Android ListView 中的 JSONArray

python - 我正在获取 AttributeError : 'list' object has no attribute 'lower' while trying to split ("") on text data