替换列表中的最小值和最大值

bla*_*rgh 0 python list

我需要帮助为列表编写一个 python 函数,它可以做两件事。

首先,它将用数字 5000(最大)和 -5000(最小)替换列表中的最大和最小元素。

thelist = input("Please input a list with numbers: ")
mylist = list(map(int, thelist.split()))
Run Code Online (Sandbox Code Playgroud)

请输入包含数字的列表:1 2 3 4 5 6 7 8 9 10

print(mylist)
Run Code Online (Sandbox Code Playgroud)

结果:[1,2,3,4,5,6,7,8,9,10]

老实说,我不知道如何使用 py 函数将 1 和 10 替换为数字 5000 和 -5000。我可以获得最小和最大数字,但替换它们是我不知道该怎么做。

小智 5

使用列表理解以稍微压缩的格式,您可以使用

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
b = [-5000 if x == min(a) else 5000 if x == max(a) else x for x in a]
Run Code Online (Sandbox Code Playgroud)

它将最小元素替换为 -5000,将最大元素替换为 5000。如果有多个最小值,则所有元素都将被替换。您可以使用函数来使用 -5000、5000 以外的其他值。