繁体   English   中英

修改后如何在原始输入订单上打印列表

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM