![](/img/trans.png)
[英]how to stop yielding of scrapy spider within for loop if a certain condition is met?
[英]How to return an argument if a certain condition is met in a loop?
import random
def lottery(lucky_numbers, run):
i = 0
while i < run:
x = random.uniform(0, 1) #prints out a random number between 0 and 1
numbers = lucky_numbers
NewNumbers = numbers[-1:] + numbers[:-1] #shifts each element in the to the right
lucky_numbers = NewNumbers
print(lucky_numbers, x)
i += 1
lottery([1, 2, 0], 3)
這段代碼輸出如下內容:
>>>>>>>>>>
[0, 1, 2] 0.33016179294984127
[2, 0, 1] 0.7797639530009745
[1, 2, 0] 0.6292245916315391
>>>>>>>>>>
x值將始終是不同的,因為它們是0到1之間的隨機數。
我試圖添加一個函數,說明如果x是循環中的最小值(最小值),則程序應打印該迭代的列表,例如,在這種情況下,此循環中x的最小值為0.33016179 ..,因此,程序應打印列表[0,1,2]
我只是將信息保存在變量中,並在循環結束后打印出來:
import random
def lottery(lucky_numbers, run):
i = 0
min_x = 1
while i < run:
x = random.uniform(0, 1) #prints out a random number between 0 and 1
numbers = lucky_numbers
NewNumbers = numbers[-1:] + numbers[:-1] #shifts each element in the to the right
lucky_numbers = NewNumbers
if x < min_x:
min_x = x
min_lucky_numbers = lucky_numbers
i += 1
print(min_lucky_numbers, min_x)
lottery([1, 2, 0], 3)
您可以創建一個存儲所有x
值的“緩存”,然后調用最低值。
cache = []
for _ in range(3):
x = random.uniform(0, 1)
cache.append(x)
print min(cache)
要執行您想要的操作,只需將項目存儲在兩個不同的列表中,對它們進行排序並顯示每個項目的firt元素:
import random
luckiest_num = list()
luckiest_list = list()
def lottery(lucky_numbers, run):
i = 0
while i < run:
x = random.uniform(0, 1)
numbers = lucky_numbers
NewNumbers = numbers[-1:] + numbers[:-1]
print(NewNumbers, x)
i += 1
luckiest_num.append(x)
luckiest_list.append(NewNumbers)
lottery([1, 2, 0], 3)
luckiest_num.sort()
luckiest_list.sort()
print ("The luckiest item is : ")
print(luckiest_num[0],luckiest_list[0])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.