【问题标题】:How to swap maximums with the minimums? (python)如何将最大值与最小值交换? (Python)
【发布时间】:2014-07-25 06:08:20
【问题描述】:

有没有办法交换列表的最大值和最小值?

列表如下,程序必须继续,以便打印最大值与最小值交换,第二个最大值与第二个最小值交换,第三个最大值与第三个最小值交换。

例如。输入输入 - 0 1 2 3 4 5 6 7 8 9 -1 输出 - 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"

【问题讨论】:

  • 我猜这是你的作业。您设法要求提供数字列表,但是您尝试任何方法来解决切换值的实际任务的尝试是什么?不要一开始就追求最好,给我们展示一些东西。
  • 只需a.reverse() 最大值列表时
  • @Streak 不是。反向将列表颠倒过来,问题是交换列表中的最小值和最大值。

标签: python max swap min


【解决方案1】:

python 中没有这种方法。您可以尝试使用原始方法来构建您想要的列表。

这段代码完成了这项工作:

#!/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

【讨论】:

    【解决方案2】:

    我假设列表不包含重复值。然后你可以构造一个新的排序列表来找到最小和最大的数字。

    之后,你从排序列表中取出相应的值,在原始列表中找到它们的索引并交换它们。

    data = list(range(10))
    helper = sorted(data)
    for i in range(3):
        low_value = helper[i]
        high_value = helper[-(i+1)]
        low_index = data.index(low_value)
        high_index = data.index(high_value)
        print(low_index, high_index)
        data[low_index], data[high_index] = data[high_index], data[low_index]
    print(data)
    

    【讨论】:

      【解决方案3】:

      对于一个简单的方法,我创建了以下内容:

      #Initial setup:
      z = [10, 8, 20, 2]
      u = [-x for x in z]
      z_copy = [x for x in z]
      weights_reversed = [None] * len(u)
      
      #algorithm
      for i in range(len(u)):
          index_F = u.index(max(u))
          u[index_F] = -10^80 # to remove that value from consideration
          index_Z = z.copy.index(max(z_copy))
          max_wt = z_copy.pop(index_Z)
          weights_reversed[index_F] = max_wt
      

      上面的结果创建了一个列表[8, 10, 2, 20]

      【讨论】:

        【解决方案4】:

        签出this

        >>> sorted(student_tuples, key=itemgetter(2), reverse=True)
        [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-05-19
          • 2019-01-09
          • 2021-03-19
          • 1970-01-01
          相关资源
          最近更新 更多