我正在尝试学习如何将这个程序更改为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
。
答案 0 :(得分:1)
我不明白为什么你为你的功能使用这个名字,它做了别的事情(据我所知)。它搜索列表中的内部列表,其中min和max之间的差异,span,是最大的,n返回元组(span, idx)
,idx
是外部循环中的索引。 / p>
当您想要与循环相同时,请尝试:
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
答案 1 :(得分:0)
如果您正在寻找最小金额,只需浏览每一行并跟踪最小值:
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()函数),那就相似了。您将跟踪最大范围并返回其索引。
托尔斯滕的回答非常完整。但是,无论如何我完成了这个,我正在提交我的“愚蠢”版本,以防它帮助你理解。
答案 2 :(得分:0)
您想要的实际上可以用两行代码完成:
# 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