gpt4 book ai didi

python - 有没有更简洁的方法来构建这个列表? python 3

转载 作者:行者123 更新时间:2023-12-04 10:47:27 25 4
gpt4 key购买 nike

我想知道是否有更简洁的方法来执行我的代码的第 3 部分?
我正在为分配构建一个井字游戏,这是检查是否有一行 3 个 X 或 O 的函数。因此,我将代表 3x3 游戏板的“棋盘”列表拆分为三个列表,分别代表行、列和“角到角”线。

def check_forwin(board,split_list):

#part 1 splice a single list into 3 lists
check_list1 = [tuple(board[i:j]) for i, j in zip([1]+ split_list, split_list)]
#part 2"invert" the list, as in choosing columns
check_list2 = list(zip(check_list1[0],check_list1[1],check_list1[2]))

#part 3 make 2 lists from "corner to corner"
check_list3 = [[],[]]

check_list3[0] = tuple([check_list1[0][0],check_list1[1][1],check_list1[2][2]])
check_list3[1] = tuple([check_list1[0][2],check_list1[1][1],check_list1[2][0]])

return

board = ["#","a","b","c","d","e","f","g","h","i"]
split_list1 = [4, 7, 10]

check_forwin(board,split_list1)

[('a', 'b', 'c'), ('d', 'e', 'f'), ('g', 'h', 'i')]
[('a', 'd', 'g'), ('b', 'e', 'h'), ('c', 'f', 'i')]
[('a', 'e', 'i'), ('c', 'e', 'g')]

最佳答案

使用列表理解使它更整洁,但是,正如 Kalma 所说,“整洁”是非常主观的。

def check_forwin(board,split_list):

#part 1 splice a single list into 3 lists
check_list1 = [tuple(board[i:j]) for i, j in zip([1]+ split_list, split_list)]

#part 2"invert" the list, as in choosing columns
check_list2 = list(zip(check_list1[0],check_list1[1],check_list1[2]))

#part 3 make 2 lists from "corner to corner"
check_list3 = [[],[]]

# Number of element in row or column
n = len(check_list1)
check_list3[0] = tuple([check_list1[i][i] for i in range(n)])
check_list3[1] = tuple([check_list1[i][n-i-1] for i in range(n)])

return

关于python - 有没有更简洁的方法来构建这个列表? python 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59636675/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com