![](/img/trans.png)
[英]How to check if a number in a list is greater than the number before it - python
[英]How do you check if an item in a list is greater than all the items before it in the list?
我正在尝试检查并循环遍历数字列表,以查看列表中数字之前的所有数字是否都小于列表中所有项目的数字。 到目前为止,这是我尝试过的:
myList = [5, 8, 2, 3, 10, 7, 12]
numberList = []
for number in myList:
if number > myList[myList.index(number) - 1]:
numberList.append(number)
但是,这只会检查列表中它前面的数字,而不是它前面的所有数字。 我想知道是否有解决此问题的方法或更好的方法来解决此问题。 我得到的 output 是 [5, 8, 3, 10, 12],而不是我想要的 [5, 8, 10, 12]。
只跟踪最大值:
myList = [5, 8, 2, 3, 10, 7, 12]
numberList = []
maxx = -1
for number in myList:
if number > maxx:
numberList.append(number)
maxx = number
使用列表理解。 海象运算符:= 在 python 3.8 之后可用,非常适合您的情况:
max = mylist[0]
[max := each for each in myList if each > max]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.