[英]How do I generate a random list more than once without using multiple if/else statements in python?
我試圖僅使用一個while循環和一個數字列表來生成列表五次。 我寫的代碼對我來說似乎不錯,但是列表只生成一次,然后為其他測試生成相同的列表。 我每次都想要一個隨機列表。 我不知道出什么問題了,所以我不知道如何解決。 任何幫助,將不勝感激。
這是我的代碼:
import random, time
number = 23
counter = 0
total = 5
counter2 = 0
current = 0
numbers = []
tally = 1
trash = []
while counter < total:
while counter2 < number:
for x in range(1):
current = random.randint(1, 366)
time.sleep(0.0001)
counter2 += 1
numbers.append(current)
numbersS = set(numbers)
size = len(numbersS)
if size < number:
print("1")
else:
print("0")
counter += 1
numbers = trash
我不知道怎么了
行numbers = trash
沒有做您想要的。 除了清空列表之外,它只會使numbers
成為trash
的同義詞。 這意味着下次您執行numbers.append(current)
您實際上將該值添加到了trash
列表中。
看下面的簡化代碼和注釋:
trash = []
numbers = []
numbers.append(1) # adds to numbers, not to trash
numbers = trash # now both names are synonyms for the same list; currently empty
numbers.append(2) # adds to trash(!)
numbers = trash # this was already the case: does not do anything
print(numbers, trash) # [2] [2]
您應該只執行numbers = []
而不是numbers = trash
。 另外,您可以使用相同的列表,並用del numbers[:]
或numbers.clear()
截斷它
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.