如何在python中迭代两个列表并按索引顺序重复较小的列表?

2024-06-18 11:56:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着遍历列表“grid”,这样我就可以得到一个模式,当每个列表到达“grid”列表中的最后一个列表时,按索引重复自身的顺序打印每个列表,直到它与pri\u score中的数字相同为止。你知道吗

我在终端上运行时没有收到任何错误消息。你知道吗

编辑: 我已经开始工作了我就是这么做的。你知道吗

pri_score = input("What did you score? ")
print mark(pri_score)
ite = 0

grid = [['0','0','1','0','0'],
['0','1','1','1','0'],
['1','1','1','1','1'],
['0','1','1','1','0'],
['0','0','1','0','0'],
['0','0','0','0','0']]

grid_index = 0

while ite < pri_score:
    if grid_index == 5:
        grid_index = 0
    else:
        grid_index += 1
        print grid[grid_index]
    ite += 1

Tags: 终端消息编辑列表inputindex顺序错误
2条回答

试试这个,可能会让你的生活更轻松:

pri_score = input("What did you score? ")
print mark(pri_score)

grid = [['0','0','1','0','0'],
['0','1','1','1','0'],
['1','1','1','1','1'],
['0','1','1','1','0'],
['0','0','1','0','0'],
['0','0','0','0','0']]

for i in range(pri_score):
    print grid[ i % len(grid) ]

重复模式的基本技巧是模运算符%,避免使用手动迭代器变量是python的标准习惯用法。你知道吗

我想,应该是:

while ite < pri_score:     # less than instead of greater than

相关问题 更多 >