如何在Python中循环列表以确保没有重复?

时间:2016-03-16 01:00:00

标签: python arrays loops python-3.x

在我的代码中,我试图为战舰生成坐标而不需要任何重复坐标。我只管理的坐标比我要求的要多得多,或者根本没有。我在循环中做错了什么/如何解决这个问题?

from random import randint

board = []  #Create an empty array to act as the game board.
ships = []  #Create an empty array to hold the locations of the random ships.

board_size = int(input("Enter your desired board size: "))          #Ask the user for their preferred board size.
ship_number = int(input("Enter the number of ships you want to find: "))    #Ask the user for their preferred ship number.

ships_found = 0 #Set the counter of the number of user-found ships to start at 0.

def generate_board(board_size):         #Define a function to generate the initial board.
    for each_item in range(board_size):     #For each item in the range of the board's size,
        board.append(["O"] * board_size)    #Append an O to the board as many time as the user's board size says.
generate_board(board_size)

def print_board(board):         #Define a function to print the current board.
    for row in board:           #For each row in the board,
        print(" ".join(row))    #Print each chacter, separated by a space.

def generate_ships(ship_number,board):
    for each_ship in range(ship_number):
        new_ship = [randint(0, len(board) - 1),randint(0, len(board) - 1)]
        for each_item in ships:
            if each_item == new_ship:
                ships.pop()
                ships.append(new_ship)
            else:
                ships.append(new_ship)

generate_ships(ship_number,board)

1 个答案:

答案 0 :(得分:0)

虽然使用set()删除重复内容会在技术上回答标题中的问题,但我建议您重新考虑您的方法(并重写generate_ships,其逻辑似乎可能不会做什么你想要它。)

您可以从random element中选择一个set of available coordinates,而不是随机生成一个坐标(在移除已有船只的坐标后,您的纸板坐标)。这样您只需选择您要求的船只数量,而不必担心检查重复。