如何将最大值与最小值互换? (Python) [英] How to swap maximums with the minimums? (python)

查看:214
本文介绍了如何将最大值与最小值互换? (Python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种方法可以交换列表的最大值和最小值?

Is there a method to swap the maximum and the minimum of a list?

列表将如下所示,该程序必须继续执行,以便将打印的最大值与最小值交换,第二个最大值与第二个最小值交换,第三个最大值与第三个最小值交换.

The list will be as follows and the program has to be continued so that it will print the maximum swapped with the minimum, the second maximum swapped with the second minimum and third maximum swapped with the third minimum.

例如.输入输入-0 1 2 3 4 5 6 7 8 9 -1 输出-9873456210

Eg. Enter input- 0 1 2 3 4 5 6 7 8 9 -1 Output- 9873456210

a = []
nums = raw_input("Enter input- ")
for n in nums.split():
    n = int(n)
    if n < 0:
        break
    a.append(n)
if len(a)<7:
    print "please enter more than 7 integers"

推荐答案

python中没有解决此问题的方法.您可以尝试使用原始方法来使用列表构建所需的内容.

There is no method for this in python. You can try using primitive methods to build what you want using lists.

此代码可以完成这项工作:

This code does the job:

#!/usr/bin/python
a = []
b = []
nums = raw_input("Enter input- ")
#append all to a list
for n in nums.split():
    n = int(n)
    if n < 0:
        break
    a.append(n)

#get the maximums
b = list(a)
first_max = max(b)
b.remove(first_max)
second_max = max(b)
b.remove(second_max)
third_max = max(b)

#get the minimums
b = list(a)
first_min = min(b)
b.remove(first_min)
second_min = min(b)
b.remove(second_min)
third_min = min(b)

## now swap 
xMax, yMax, zMax = a.index(first_max), a.index(second_max), a.index(third_max)
xMin, yMin, zMin = a.index(first_min), a.index(second_min), a.index(third_min)
a[xMax], a[xMin] = a[xMin], a[xMax]
a[yMax], a[yMin] = a[yMin], a[yMax]
a[zMax], a[zMin] = a[zMin], a[zMax]

print a

这篇关于如何将最大值与最小值互换? (Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆