Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/backbone.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Can';t在Python中从随机列表中删除重复项_Python - Fatal编程技术网

Can';t在Python中从随机列表中删除重复项

Can';t在Python中从随机列表中删除重复项,python,Python,我正在用Python创建一个战舰游戏,但我想随机生成一个数字列表作为它们的位置。但是,我不能删除重复项,我可以使用set(),但它不会给出我需要的5个结果 #Battleships challenge import random place = []#empty list for i in range(5): place.append(random.randrange(1,50,1)) print(place) ships =len(place) hits

我正在用Python创建一个战舰游戏,但我想随机生成一个数字列表作为它们的位置。但是,我不能删除重复项,我可以使用set(),但它不会给出我需要的5个结果

#Battleships challenge
import random

place = []#empty list
for i in range(5):
               place.append(random.randrange(1,50,1))

print(place)
ships =len(place)


hits = 0
misses = 0
counter = 0
while ships > 0:
               hit = int(input("Which space do you want to hit?"))
               if hit in place:
                              place.remove(hit) 
                              print("You have a hit!")
                              ships = ships -1
                              hits = hits + 1
               else:
                              print("No!")
                              misses = misses + 1

if ships == 0:
               print("Well done, all ships have disappeared!")
               print(hits, "successful hits")
               print(misses,"misses")
我想会有用的


我想会有用的

谢谢!我确实尝试过随机抽样,但不是那样,它现在起作用了!谢谢我确实尝试过随机抽样,但不是那样,它现在起作用了!
all_positions = range(100)
five_positions = random.sample(all_positions,5)