简体   繁体   中英

How to print a list on the original inputted order after modifying it

For this lab, I need to 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, adjust each integer in the list by subtracting the smallest value from all the integers. My code runs and I am getting the correct outputs, but the code is meant to output the new integers(after subtracting the smallest value) in the order they were inputted. However, because I sorted the list in the beginning of my program, the numbers are printing in order from smallest to biggest. How do I get them to print in my final statement in the same order that they were inputted? For example, if the numbers inputted were 30, 50, 10, 70, 65, they should output 20, 40, 0, 60, 55. But my program is outputting them as 0, 20, 40, 55,60.

This is the code I have so far:

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)

Instead of sorting the list, you can use a different Python built in function, min(), which takes the smallest number in a list. Using this, you won't need to sort the list, keeping the original order, and just subtract each element in the list by the int you got from min().

Here it is:

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)

Just making small changes in your code

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 showing order is not changed

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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