遍历字典以在另一个列表中创建项目列表

时间:2018-10-10 15:48:07

标签: python python-3.x list dictionary for-loop

我有一本叫做《舰队少舰》的字典。字典中的每艘船都长于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()

1 个答案:

答案 0 :(得分:0)

很抱歉,要求不清楚。

在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])