简体   繁体   English

检查项目是否存在于每个嵌套列表中的相同 position - Python

[英]Check if item exists in same position in each nested list - Python

I'm writing a Connect Four script.我正在写一个 Connect Four 脚本。 The script takes a list of moves as input ( "A_Red, "B_Yellow", "G_Red" , etc), which I'm sorting into a matrix. Each nested list represents a column of the board with "A" being the first nested list (or column), and "G" being the last nested list (or column). Moves will then get sorted like so:该脚本将移动列表作为输入( "A_Red, "B_Yellow", "G_Red"等),我将其分类为矩阵。每个嵌套列表代表棋盘的一列,其中“A”是第一个嵌套列表(或列),“G”是最后一个嵌套列表(或列)。移动将像这样排序:

A board with some moves will resemble something like:带有一些动作的棋盘类似于:

[ ["Red, "Yellow"], ["Red"], ["Yellow", "Yellow"], [], [], [], [] ]

Once all of the moves are sorted into their respective nested list, I fill each nested list with empty strings ("") to prevent any 'list index out of range errors' with for loops used to perform 4-in-a-row checks.一旦所有的移动都被分类到它们各自的嵌套列表中,我用空字符串 ("") 填充每个嵌套列表,以防止任何“列表索引超出范围错误”,用于执行 4 行检查的for循环.

How can I check if the 4th element ( index[3] ) of each nested list contains either "Red" or "Yellow" WITHOUT a for loop?如何在没有for循环的情况下检查每个嵌套列表的第 4 个元素 ( index[3] ) 是否包含"Red""Yellow"

If this condition is True, the diagonal checks will then be performed, and I only need them performed once.如果此条件为真,则将执行对角线检查,我只需要执行一次。

board = [["Red", "Yellow", "Red", "Yellow"], [], [], ["Red", "Yellow", "Red", "Yellow"], [], [], []]
for i in range (0, 7):
   if board[i][3]:
       # Perform Diagonal Check

The issue with the above code is that I only need the diagonal check to be performed one time when any "Red" or "Yellow" piece is identified in the fourth position in any nested list.上面代码的问题是,当在任何嵌套列表中的第四个 position 中识别出任何“红色”或“黄色”部分时,我只需要执行一次对角线检查。 With the above for loop, the check will be performed 7 times for each item in the fourth position.通过上面for循环,会对第四个position中的每一项进行7次检查。

Is it possible to check a range of list positions without going:是否可以在不去的情况下检查一系列列表位置:

if board[0][3] or board[1][3] or board[2][3]... == "Yellow" or "Red": #etc...

To check the 4th element in each sub-list, use the following code:要检查每个子列表中的第 4 个元素,请使用以下代码:

mylist = [[1, 2, 3, 0, 4], [5, 6, 7, 0, 8], [9, 1, 2, 0, 3]]

fourth_element_check = [x[3] for x in mylist]

if 0 in fourth_element_check:
    print ("0 is the fourth element of a list")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM