首页 > 解决方案 > 遍历字典以在另一个列表中创建项目列表

问题描述

我有一本字典,叫做舰队少船。字典中的每艘船都比 1 长(至少包含两组坐标,例如[[3, 1], [3, 2]][[2, 3], [2, 4], [2, 5]].

使用下面的代码,我设法获得了所有船只的坐标,但不知何故,我无法弄清楚如何制作舰队列表,其中的每个元素都是带有坐标的列表列表。对于上面的示例,我需要这样的结果:

[[[3, 1], [3, 2]],
 [[2, 3], [2, 4], [2, 5]]]

我想需要另一个for循环,但我无法正确集成它。

有问题的代码在函数 place_ship()

num_cols = 5  # board size direction x
num_rows = 4  # board size direction y
empty_field = "~"

fleet = {
"Submarine": [3, "S"],
"Patrol Boat": [2, "P"]
}

def place_ship():
    # place ship based on orientation
    list_ship_coordinates = []
    if ori == "v":
        for i in range(fleet[ship][0]):
            board[x + i][y] = fleet[ship][1]
            part_of_ship = [x + i + 1, y + 1]
            list_ship_coordinates.append(part_of_ship)
        print(list_ship_coordinates)
    elif ori == "h":
        for i in range(fleet[ship][0]):
            board[x][y + i] = fleet[ship][1]
            part_of_ship = [x + 1, y + i + 1]
            list_ship_coordinates.append(part_of_ship)
        print(list_ship_coordinates)
    return board


def validate():
    if ori == "v" and x + fleet[ship][0] > num_rows:
        return False
    elif ori == "h" and y + fleet[ship][0] > num_cols:
        return False
    else:
        if ori == "v":
            for i in range(fleet[ship][0]):
                if board[x + i][y] != empty_field:
                    return False
        elif ori == "h":
            for i in range(fleet[ship][0]):
                if board[x][y + i] != empty_field:
                    return False
    return True


for ship in fleet:
    valid = False
    while not valid:
        x = randint(0, num_rows - 1)
        y = randint(0, num_cols - 1)
        o = randint(0, 1)
        if o == 0:
            ori = "v"
        else:
            ori = "h"
        valid = validate()
    board = place_ship()

标签: pythonpython-3.xlistdictionaryfor-loop

解决方案


抱歉没有问清楚。

原来 place_ship 函数中的新行 71 和 78 解决了我的问题。

from random import randint

num_cols = 5  # board size direction x
num_rows = 4  # board size direction y
empty_field = "~"
cheat_mode = 1  # 1 = Yes; 0 = No
line1 = "   "
line2 = "------"

# Type and quantity of ships in fleet
fleet = {
    "Aircraft Carrier": [5, "A"],
    "Battleship": [4, "B"],
    "Destroyer": [3, "D"],
    "Submarine": [3, "S"],
    "Patrol Boat": [2, "P"]
}

all_ship_parts = []
for ship in fleet:
    all_ship_parts1 = fleet[ship][0]
    all_ship_parts.append(all_ship_parts1)

all_ship_parts = sum(all_ship_parts)
num_of_turns = all_ship_parts + 1

board = []
# Create a blank board.
for each_row in range(num_rows):
    board_col = []
    for each_col in range(num_cols):
        board_col.append(empty_field)
    board.append(board_col)


def print_board():
    print("    ", end="")
    for i in range(0, num_cols):
        print(" " + str(i + 1) + " ", end=' ')
        print(" ", end=' ')
    print("")
    print(line1 + line2 * num_cols)

    for i in range(0, num_rows):
        if i < 9:
            print(str(i + 1) + " | ", end=' ')
        else:
            print(str(i + 1) + "| ", end=' ')
        for j in range(0, num_cols):
            if board[i][j] == empty_field:
                print(" ", end=' ')
            else:
                print(board[i][j], end=' ')
            print(" | ", end=' ')
        print("")
        print(line1 + line2 * num_cols)


# print_board()
total = []


def place_ship():
    # place ship based on orientation
    list_ship_coordinates = []
    if ori == "v":
        for i in range(fleet[ship][0]):
            board[x + i][y] = fleet[ship][1]
            part_of_ship = [x + i + 1, y + 1]
            list_ship_coordinates.append(part_of_ship)
        total.append(list_ship_coordinates)
        print(list_ship_coordinates)
    elif ori == "h":
        for i in range(fleet[ship][0]):
            board[x][y + i] = fleet[ship][1]
            part_of_ship = [x + 1, y + i + 1]
            list_ship_coordinates.append(part_of_ship)
        total.append(list_ship_coordinates)
        print(list_ship_coordinates)

    return board


def validate():
    if ori == "v" and x + fleet[ship][0] > num_rows:
        return False
    elif ori == "h" and y + fleet[ship][0] > num_cols:
        return False
    else:
        if ori == "v":
            for i in range(fleet[ship][0]):
                if board[x + i][y] != empty_field:
                    return False
        elif ori == "h":
            for i in range(fleet[ship][0]):
                if board[x][y + i] != empty_field:
                    return False
    return True


for ship in fleet:
    valid = False
    while not valid:
        x = randint(0, num_rows - 1)
        y = randint(0, num_cols - 1)
        o = randint(0, 1)
        if o == 0:
            ori = "v"
        else:
            ori = "h"
        valid = validate()
    board = place_ship()

print("-----------")
print(total)
print("-----------")
print(len(total))
print(sum(len(x) for x in total))
print("-----------")
print_board()
# print(board[0][2])
# print(board[1][2])
# print(board[2][2])
# print(board[3][2])

推荐阅读