我发现当前代码与回答列表中找到前两个值的问题有关,但是,我无法理解部分代码,在其他地方找不到任何帮助。我想知道是否有人可以告诉我个别部分是什么意思?
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
答案 0 :(得分:2)
这是一个粗略的伪代码:
我已经用以下解释对下面的代码进行了评论:
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