为了了解两种方式,我正在尝试学习如何将此程序更改为for循环
def Diff(a_list):
num = enumerate(max(x) - min(x) for x in a_list)
return max(x[::-1] for x in num)
我希望它像
def Diff(x):
for a in x
如果它有帮助,则程序旨在返回其中元素总和最小的行,就像[[1,2,3,4],[-500],[10,20]]
这样1
。
为了了解两种方式,我正在尝试学习如何将此程序更改为for循环
def Diff(a_list):
num = enumerate(max(x) - min(x) for x in a_list)
return max(x[::-1] for x in num)
我希望它像
def Diff(x):
for a in x
如果它有帮助,则程序旨在返回其中元素总和最小的行,就像[[1,2,3,4],[-500],[10,20]]
这样1
。
我不明白你为什么在你的函数中使用这个名字,它做了别的事情(据我所知)。它在一个列表中搜索内部列表,其中 min 和 max 之间的差异、跨度是最大的,并且 n 返回一个 tuple (span, idx)
,idx
作为外部循环中的索引。
当您想要与循环相同时,请尝试:
def minRow_loop(a_list):
rv = (0,0)
for idx, row in enumerate(a_list):
span = max(row) - min(row)
span_and_idx = (span, idx)
if span_and_idx > rv:
rv = span_and_idx
return rv
但是你的代码没有做它打算做的事情,所以我创建了两个正确的版本,一次有循环,一次没有循环。
import random
random.seed(12346)
def minRow(a_list):
num = enumerate(max(x) - min(x) for x in a_list)
return max(x[::-1] for x in num)
def minRow_loop(a_list):
rv = (0,0)
for idx, row in enumerate(a_list):
span = max(row) - min(row)
span_and_idx = (span, idx)
if span_and_idx > rv:
rv = span_and_idx
return rv
def minRow_correct(a_list):
return min(enumerate([sum(l) for l in a_list]),
key=lambda (idx, val): val)[0]
def minRow_correct_loop(a_list):
min_idx = 0
min_sum = 10e50
for idx, list_ in enumerate(a_list):
sum_ = sum(list_)
if sum_<min_sum:
min_idx = idx
min_sum = sum
return min_idx
li = [[random.random() for i in range(2)] for j in range(3)]
from pprint import pprint
print "Input:"
pprint(li)
print "\nWrong versions"
print minRow(li)
print minRow_loop(li)
打印:
Input:
[[0.46318380478657073, 0.7396007585882016],
[0.38778699106140135, 0.7078233515518557],
[0.7453097328344933, 0.23853757442660117]]
Wrong versions
(0.5067721584078921, 2)
(0.5067721584078921, 2)
Corrected versions
2
2
如果您正在寻找最小总和,只需遍历每一行并跟踪最小的:
def minRow(theList):
foundIndex = 0 # assume first element is the answer for now.
minimumSum = sum(theList[0])
for index, row in enumerate(theList):
if sum(row) < minimumSum:
foundIndex = index
minimumSum = sum(row) # you don't have to sum() twice, but it looks cleaner
return foundIndex
如果您正在寻找最大范围(如第一个 Diff() 函数),它会是相似的。您将跟踪最大范围并返回其索引。
Thorsten 的回答非常完整。但既然我已经完成了这个,我提交了我的“愚蠢”版本,以防它帮助你理解。
您想要的实际上可以在两行代码中完成:
# Let's take the list from your example
lst = [[1,2,3,4],[-500],[10,20]]
# Create a new list holding the sums of each sublist using a list comprehension
sums = [sum(sublst) for sublst in lst]
# Get the index of the smallest element
sums.index(min(sums)) # Returns: 1