[英]Python: How to stop a loop after 20 times and print the results on a user inputted list?
[英]How to print a list on the original inputted order after modifying it
對於這個實驗,我需要編寫一個程序,首先從輸入中獲取整數列表。 輸入以 integer 開頭,指示后面的整數個數。 然后,通過從所有整數中減去最小值來調整列表中的每個 integer。 我的代碼運行並且我得到了正確的輸出,但是代碼是為了 output 新整數(減去最小值后)按照輸入的順序。 但是,因為我在程序開始時對列表進行了排序,所以數字是按從小到大的順序打印的。 如何讓它們按照輸入的順序打印在我的最終聲明中? 例如,如果輸入的數字是 30、50、10、70、65,它們應該是 output 20、40、0、60、55。但我的程序輸出它們為 0、20、40、55、60。
這是我到目前為止的代碼:
x = int(input('Enter the number of integers in the data set: '))
print('Enter the', x, 'numbers: ')
list = []
for i in range(x):
x = int(input())
list.append(x)
list.sort()
smallest = list[0]
print('The smallest value is:', smallest)
print('The normalized data set is:')
for num in list:
print(num - smallest)
您可以使用 function, min() 中內置的不同 Python,而不是對列表進行排序,它采用列表中的最小數字。 使用它,您不需要對列表進行排序,保持原始順序,只需將列表中的每個元素減去從 min() 獲得的 int。
這里是:
x = int(input('Enter the number of integers in the data set: '))
print('Enter the', x, 'numbers: ')
lst = []
for i in range(x):
x = int(input())
lst.append(x)
smallest = min(lst)
print('The smallest value is:', smallest)
print('The normalized data set is:')
for num in list:
print(num - smallest)
只需對您的代碼進行一些小改動
x = int(input('Enter the number of integers in the data set: '))
print('Enter the', x, 'numbers: ')
# Using list comprehensive
input_list = [int(input()) for _ in range(x)]
# You can use below code if you want better readability
# for i in range(x):
# x = int(input())
# input_list.append(x)
# Min returns you minimum value from iterator
smallest = min(input_list)
print('The smallest value is:', smallest)
print('The normalized data set is:')
for num in input_list:
print(num - smallest)
Output 顯示順序未更改
Enter the number of integers in the data set: 3
Enter the 3 numbers:
3
2
1
The smallest value is: 1
The normalized data set is:
2
1
0
Process finished with exit code 0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.