简体   繁体   中英

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

I'm writing a Connect Four script. 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 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.

How can I check if the 4th element ( index[3] ) of each nested list contains either "Red" or "Yellow" WITHOUT a for loop?

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. With the above for loop, the check will be performed 7 times for each item in the fourth position.

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:

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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