這個問題之前已經發布過,但我無法while按照教授的指示將我當前編碼的內容翻譯成回圈。問題是:
Write a program that first gets a list of integers from input. The input begins
with an integer indicating the number of integers that follow. Then, get the
last value from the input, which indicates a threshold. Output all integers less
than or equal to that last threshold value.
Ex: If the input is:
5
50
60
140
200
75
100
The output is:
50,60,75
The 5 indicates that there are five integers in the list, namely 50,
60, 140, 200, and 75. The 100 indicates that the program should output all
integers less than or equal to 100, so the program outputs 50, 60, and 75.
For coding simplicity, follow every output value by a comma, including the last one.
Such functionality is common on sites like Amazon, where a user can filter results.
我當前的代碼在末尾包含一個“for”回圈:
make_string = []
while True:
user_input = int(input())
make_string.append(int(user_input))
if len(make_string) > (int(make_string[0]) 1):
break
end_num = make_string[-1]
make_string.pop(0)
make_string.pop(-1)
for val in make_string:
if val <= end_num:
print(val, end=", ")
有什么方法可以將最后一個for回圈轉換為while回圈以滿足我教授的要求?
uj5u.com熱心網友回復:
我會使用 for 回圈將每個輸入掃描到一個陣列中,然后使用另一個 for 回圈遍歷陣列并只列印那些小于最大值的數字,如下所示:
import array
usr_in = input() # get num inputs
if not usr_in.isnumeric(): # check that input is number
print("you enterd " usr_in ", which is no-numeric")
# cast string usr_in to type int to work with int
number_of_new_inputs = int(usr_in)
array_of_inputs = array.array('i')
# loop number_of_new_inputs times
for i in range(number_of_new_inputs):
usr_in = input() # ask for number
if not usr_in.isnumeric(): # check that it's a number
print("you enterd " usr_in ", which is no-numeric")
# add it to the list
array_of_inputs.append(int(usr_in))
usr_in = input() # get max value
if not usr_in.isnumeric(): # check that input is number
print("you enterd " usr_in ", which is no-numeric")
# cast to int
max_val = int(usr_in)
for num in array_of_inputs: # loop through the array of inputs
if num <= max_val: # if the number is smaller then the max
print(num) # print it out
uj5u.com熱心網友回復:
你可以像這樣轉換它。它將給出與您的 for 回圈相同的結果。
length = len(make_string)
i = 0
while i < length:
if make_string[i] <= end_num:
print(make_string[i],end=", " )
i = 1
uj5u.com熱心網友回復:
您可以使用串列理解將多個輸入直接放入一個串列中,而不是使用 while 回圈來獲取輸入并附加到字串中。
x = [int(x) for x in input("Enter multiple value: ").split()]
現在您有一個包含所有輸入值的串列 x。
現在,串列中的第一個元素指示要考慮的值的數量,您可以將其視為:
n = x[0]
接下來,為接下來的 n 個數字運行 for 回圈:
requiredNumbers = []
for i in range(1,n): #using range from 1 since we dont need the 1st element which is n itself
requiredNumbers.append(x[i])
現在您在我們創建的新串列中擁有所需的數字。并且目標在您的 n 1 元素中,因此您可以通過以下方式獲得它:
target = x[n 1]
現在,您可以簡單地在 requiredNumbers 串列上運行 for 回圈并與目標進行比較并檢查其是否較低并列印。
您可以通過在我們上面使用的單個 for 回圈中執行所有這些操作來簡化這一點,但為了清楚起見,我分步撰寫。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/338000.html
標籤:Python
