Как проверить, содержит ли каждая строка в двумерном массиве хотя бы 2 элемента? - PullRequest
0 голосов
/ 19 декабря 2018

Прямо сейчас у каждого элемента есть только один элемент:

dots_list = [ [1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17],[18],[19],[20],[21] ]

Как бы я вышел из цикла while, исходя из состояния каждого элемента, имеющего как минимум 2 элемента, где второй элемент является точкой.

dots_list = [ [1 . . . .],[2 ..],[3 . .],[4 .],[5 .],(...), [20 . .], [21 . ] ]

Общее количество точек не имеет значения, поскольку их может быть бесконечное количество.Важной частью является то, как завершить цикл, когда все числа в списке имеют хотя бы одну точку.

Вы можете игнорировать большую часть кода, так как у меня эта часть работает, хотя не уверен насчет условия цикла.

pd = [ #This is the visual of the pyramid

[                 1                    ], #[0][0]  row and total col# ex [2][1] = 5
[              2,    3                 ], #[1][1]
[            4,   5,    6,             ], #[2][2]
[         7,   8,    9,   10,          ], #[3][3]
[      11,  12,   13,  14,   15,       ], #[4][4]
[    16,  17,   18,  19,  20,    21,   ], #[5][5]

]

x = 0 # represents left and right direction in pd -- adding goes right, subtracting goes left
y = 5 # represents up and down direction in pd -- adding goes down, subtracting goes up

lower_bound = 1 #used as lower bound in dice selection
upper_bound = 4 #used as upper bound in dice selection

move_counter = 0 #used to count the total number of moves made in game

print("Starting position: ",pd[y][x])  # The starting position used for debugging
start_position = pd[y][x] # The starting point of the game [y][x] up/down y, left/right x

#     ----  loop begin ----
#while()


random_roll = random.randint(lower_bound, upper_bound) # Randomly selects a number from 1 to 4 to be used as fair die roll
print("Random Roll: " ,random_roll)
#--------------------------------pd bounds checking-------------------------------------------
if random_roll == 1  and (pd[y][x]) != 2 \
        and (pd[y][x]) != 4 and (pd[y][x]) != 11 and (pd[y][x]) != 16:
   #--------------------------------pd bounds checking-------------------------------------------

    print('upper left')
   # print('x: ', x, 'y:', y)

    if pd[y][x] == 1:
        print('Invalid Direction --  Move Count Increased')
        move_counter += 1
    else:
        new_pos = pd[y-1][x-1]
        y-=1
        x-=1
        #print('x: ', x, 'y:', y)
        print('new pos: ' , new_pos)
        start_position = new_pos
        print('st pos', start_position)

        move_counter += 1

#--------------------------------pd bounds checking-------------------------------------------
elif random_roll == 2  and (pd[y][x]) != 3 \
        and (pd[y][x]) != 6 and (pd[y][x]) != 10 and (pd[y][x]) != 15 and (pd[y][x]) != 21:
    # --------------------------------pd bounds checking-------------------------------------------
    print('upper right')
    #print('x: ', x, 'y:', y)

    if pd[y][x] == 1:
        print('Invalid Direction --  Move Count Increased')
        move_counter += 1
    else:
        new_pos = pd[y-1][x]
        y-=1
        x+=1
       # print('x: ', x, 'y:', y)
        print('new pos: ' , new_pos)
        start_position = new_pos
        print('st pos', start_position)
        move_counter += 1


#--------------------------------pd bounds checking-------------------------------------------
elif random_roll == 3 and (pd[y][x]) != 16 and (pd[y][x]) != 17 \
        and (pd[y][x]) != 18 and (pd[y][x]) != 19 and (pd[y][x]) != 20 and (pd[y][x]) != 21:
# --------------------------------pd bounds checking-------------------------------------------
    print(' down left')

    #print('x: ', x, 'y:', y)
    new_pos = pd[y+1][x]
    x-=1
    y+=1
   # print('x: ', x,  'y:' , y)
    print('new pos: ' , new_pos)
    start_position = new_pos
    print('st pos', start_position)
    move_counter += 1

#--------------------------------pd bounds checking-------------------------------------------
elif random_roll == 4 and (pd[y][x]) != 16 and (pd[y][x]) != 17 \
        and (pd[y][x]) != 18 and (pd[y][x]) != 19 and (pd[y][x]) != 20 and (pd[y][x]) != 21 :
# --------------------------------pd bounds checking-------------------------------------------
    print('down right')

   # print('x: ', x, 'y:', y)
    new_pos = pd[y+1][x+1]
    x+=1
    y+=1

   # print('x: ', x, 'y:', y)
    print('new pos: ' , new_pos)
    start_position = new_pos
    print('st pos', start_position)
    move_counter += 1

else:
    print('Invalid Direction --  Move Count Increased')
    start_position = pd[y][x]
    print('st pos', start_position)
    move_counter += 1

# ---- loop end ----

1 Ответ

0 голосов
/ 19 декабря 2018

Вы можете использовать функцию any и перебирать элементы вашего списка с пониманием, которое проверяет, является ли длина какого-либо элемента меньше 2. Если какой-либо элемент короче 2, то цикл продолжится, как только вседлина элементов не менее 2, цикл прекратится.

Например:

while any(len(x) < 2 for x in pd):
    # do stuff

Где pd - это ваш 2-й список из вашего примера.

...