我需要帮助理解代码的一部分 - Python

时间:2016-08-30 11:13:44

标签: python-3.x

我发现当前代码与回答列表中找到前两个值的问题有关,但是,我无法理解部分代码,在其他地方找不到任何帮助。我想知道是否有人可以告诉我个别部分是什么意思?

numbers = [20,67,3,2.6,7,74,2.8,90.8,52.8,4,3,2,5,7]
if numbers[0]>numbers[1]:
    m, m2 = numbers[0], numbers[1]
else:
    m, m2 = numbers[1], numbers[0]
for x in numbers[1:]:
    if x>m2:
        if x>m:
            m2, m = m, x # I am especially unsure of what is going on here
        else:
            m2 = x

m2返回74

1 个答案:

答案 0 :(得分:2)

这是一个粗略的伪代码:

  1. m将跟踪列表中的最大变量,m2将跟踪第二大变量。
  2. 最初m和m2只是列表中的前两个元素,m将是前两个中较大的元素,而m2将是前两个中较小的元素
  3. 然后迭代从索引1开始的列表,对于每个元素x,首先检查它是否大于当前m2。如果是,则需要更新m2,因为它不再是第二大元素。你还需要检查x是否大于m(这应该是列表中最大的元素),如果是,则将m更新为x,m2更新为m先前
  4. 我已经用以下解释对下面的代码进行了评论:

    numbers = [20,67,3,2.6,7,74,2.8,90.8,52.8,4,3,2,5,7]   # list
    # This part sets m1 and m2 to be the bigger of the first two elements in the list. 
    # The notation m,m2 = numbers[0], numbers[1] is equivalent to m = numbers[0] followed by m2 = numbers[1]
    if numbers[0]>numbers[1]:      
        m, m2 = numbers[0], numbers[1]
    else:
        m, m2 = numbers[1], numbers[0]
    for x in numbers[1:]:         # iterate over list start at index 1
        if x>m2:                  # if current element is greater than m2, we need to update m2
            if x>m:               # if current element is also greater than m, we need to set m2 to the value of m, and then update m to the new largest value which is x.
                m2, m = m, x      # This is doing m2 = m followed by m = x
            else:
                m2 = x            # if current element is greater than m2 but not m, just update m2 to x
    

    上面的代码很好,很明确,所以如果你从Python开始是好的。还有一个班轮比你会这样做:

    m, m2 = sorted(numbers, reverse=True)[:2]
    

    说明:

    sorted(numbers, reverse=True)                 # => returns sorted version of numbers [90.8, 74, 67, 52.8, 20, 7, 7, 5, 4, 3, 3, 2.8, 2.6, 2]
    sorted(numbers, reverse=True)[:2]             # => splices the list to the first two elmems i.e [90.8, 74]
    m, m2 = sorted(numbers, reverse=True)[:2]     # => Does the confusing multiple assignment as m = first element of the list and m2 = second element of the list