![](/img/trans.png)
[英]How do I take the nth element of a list and compare to the last nth elements of the same list
[英]Iterate and compare nth element with the rest of elements in list
我有一个整数列表,必须检查右边的所有整数(因此,从每个整数到列表末尾)是否都严格小于我正在迭代的整数。
例如,对于[42, 7, 12, 9, 2, 5]
我必须比较42
是否大于[7, 12, 9, 2, 5]
,如果7
大于[12, 9, 2, 5]
依此类推到列表的末尾。
function 必须返回大于列表中 rest 的数字数量,包括最后一个 - 因为它后面没有更大的数字。
我现在的代码:
def count_dominators(items):
if len(items)< 2:
return len(items)
dominators_count = 0
for ind, el in enumerate(items[0:-1]):
if el > items[ind+1]:
dominators_count += 1
pass
我已经尝试使用嵌套for
循环进行迭代,使用enumerate()
并使用itertools.combinations()
对其进行迭代,并结合这些方法,但无济于事 - 我通常将TypeError
链接到迭代(例如列表索引出范围,即使我使用切片来避免它)。
我建议使用enumerate
用它们的索引迭代项目(正如你已经在做的那样),然后使用all
迭代给定项目之后的所有项目,并sum
all
结果的总和:
>>> def count_dominators(items):
... return sum(all(n > m for m in items[i+1:]) for i, n in enumerate(items))
...
>>> count_dominators([42, 7, 12, 9, 2, 5])
4
另一种方法是与剩余项目的max
进行比较,尽管这样你需要对列表的末尾进行特殊处理(对于空列表, all
返回True
,但max
会引发异常):
>>> def count_dominators(items):
... return sum(n > max(items[i+1:]) for i, n in enumerate(items[:-1])) + 1
...
>>> count_dominators([42, 7, 12, 9, 2, 5])
4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.