如何使用给定列表的for循环在Python中反转索引值 [英] How to reverse the index value in Python using for loop with a given list

查看:41
本文介绍了如何使用给定列表的for循环在Python中反转索引值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个函数,该函数可以打印带有给定列表的井字棋盘,该索引将其索引值以相反的顺序排列在棋盘上,例如从9到1的数字键盘(第1个)索引值为7、8、9的行:第二行4、5、6:第三行的1、2、3.

I want to create a function that prints out a tic-tac-toe board with a given list that position its index value on the board in a reverse order like on a number keyboard that is from 9 to 1, with the 1st row having the index value of 7, 8, 9: 2nd row 4, 5, 6: 3rd row 1, 2, 3.

例如:给定列表

test_board = ['O','O','X','X','X','O','X','O','X']

该节目打印如下:

 X | O | X 
---|---|---
 X | X | O 
---|---|---
 O | O | X  

我写了这个函数:

def display_board(board):

    h_sep = '-' * 3
    for i in range(3):

        for j in reversed(board[1:]):

            print(f"{j:^3}|{j:^3}|{j:^3}")

        if i != 2:
            print(f"{h_sep:^3}|{h_sep:^3}|{h_sep:^3}")

但是当我使用给定列表调用函数时,我得到了以下打印内容:

But i get this print out when i call the function with the given list:

test_board = ['O','O','X','X','X','O','X','O','X']
display_board(test_board)

输出:

 X | X | X 
 O | O | O 
 X | X | X 
 O | O | O 
 X | X | X 
 X | X | X 
 X | X | X 
 O | O | O 
---|---|---
 X | X | X 
 O | O | O 
 X | X | X 
 O | O | O 
 X | X | X 
 X | X | X 
 X | X | X 
 O | O | O 
---|---|---
 X | X | X 
 O | O | O 
 X | X | X 
 O | O | O 
 X | X | X 
 X | X | X 
 X | X | X 
 O | O | O 

我可以使用 for循环来实现此目的,而无需编写如下多个打印语句:

Edited: Can i use for loop to achieve this without writing multiple print statement like this:

print(f"{board[6]:^3}|{board[7]:^3}|{board[8]:^3}")
print(f"{h_sep:^3}|{h_sep:^3}|{h_sep:^3}")
print(f"{board[3]:^3}|{board[4]:^3}|{board[5]:^3}")
print(f"{h_sep:^3}|{h_sep:^3}|{h_sep:^3}")
print(f"{board[0]:^3}|{board[1]:^3}|{board[2]:^3}")

推荐答案

第二秒钟,您将打印3次,然后转到下一行.

In your second for you are printing it 3 times before going to the next line.

经过以下修改的函数可以解决您的问题:

Your function with the following modifications would work for your problem:

def display_board(board):
h_sep = '-' * 3
for i in reversed(range(3)):

    print(f"{board[i*3]:^3}|{board[i*3+1]:^3}|{board[i*3+2]:^3}")

    if i != 0:
        print(f"{h_sep:^3}|{h_sep:^3}|{h_sep:^3}")

这篇关于如何使用给定列表的for循环在Python中反转索引值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆