在Python中通过用户输入进行最大值和最小值排序

2024-10-04 07:36:59 发布

您现在位置:Python中文网/ 问答频道 /正文

伙计们,我想按照用户输入值的升序和降序对预定义列表进行排序。它假设从用户处获取一个最大值和最小值,并在列表中查看这些值,然后按升序和降序打印。IDK如何使用范围函数来完成这个任务,所以如果有人可以帮助,请:D这里是我做的代码,并希望使用该列表

userInputMax = input("Please enter max value")
userInputMin = input("Please enter min value")

priceList = [399, 4369, 539, 288, 109, 749, 235, 190, 99, 1000]

print(priceList)

如果用户说最大值为1000,最小值为99,那么输出应该类似于99、109、235、288、399、539、749、1000


Tags: 函数代码用户列表input排序valuepricelist
3条回答

如果您试图使列表包含从最小到最大的数字,那么您可以使用列表理解创建一个列表,使用范围函数包含从最小到最大的所有数字

priceList = [i for i in range(int(userInputMin), int(userInputMax))]

这个怎么样

def condition(x,usermax,usermin):
    '''Define your arbitrarily
    complicated condition here'''
    return x<=usermax and x>=usermin

priceList = [399, 4369, 539, 288, 109, 749, 235, 190, 99, 1000]

# Filter out all elements that do
# not meet condition
filtered = [x for x in priceList if condition(x,userInputMax,userInputMin)]
filtered.sort()

print(filtered)

这就是你要找的吗

try:
  max = int(input("Please enter max value: "))
  min = int(input("Please enter min value: "))
except ValueError:
  raise ValueError('Inserted value is not number')

priceList = [399, 4369, 539, 288, 109, 749, 235, 190, 99, 1000]
priceList.sort()

filtered_priceList = list(filter(lambda x: x < max and x > min, priceList))

print('resulted list is', filtered_priceList)

Please enter max value: 200
Please enter min value: 900
resulted list is [235, 288, 399, 539, 749]

相关问题 更多 >