繁体   English   中英

查找列表中的值是否大于其下方的项目

[英]Finding if a value in a list is greater than the item below it

我已经为此寻找解决方案一段时间了,虽然我有一些理解,但我不能让它按预期工作。 我希望我能得到一些见解:

所以我有一个包含数字的列表:

refl = ["100", "99", "90", "80", "60", "50", "10"]

我想知道第一项是否大于第二项,如果第二项大于第三项,第三项是否大于第四项,等等。

我想我正在努力如何捕获初始列表 object 以将其与下一个进行比较......?

任何帮助将不胜感激,

****编辑以添加功能*****

我有以下 function:

refl = ["100", "99", "90", "80", "60", "50", "10"]

def funcc(refl):
    if (refl[0]) > (refl[1]):
        print("more")
    else:
        print("less")

我如何让 function 遍历列表中的每个 object 而无需隐式指定 [1] > [2]、[2] > [3] 等

非常感谢,

您可以将列表zip()成对,然后检查每对中的第一项是否大于第二项。 我假设你想在这里进行 integer 比较。 如果没有,您可以删除int()强制转换,它将使用它们各自的 ASCII 值按字典顺序比较字符串。

然后,您可以使用all()检查每对是否满足此条件。

>>> refl = ["100", "99", "90", "80", "60", "50", "10"]
>>> all(int(fst) > int(snd) for fst, snd in zip(refl, refl[1:]))
True

如果您只想从每个比较中捕获 boolean 结果,您可以使用列表推导:

>>> [int(fst) > int(snd) for fst, snd in zip(refl, refl[1:])]
[True, True, True, True, True, True]

这是您现有的代码:

def funcc(refl):
    if (refl[0]) > (refl[1]):
        print("more") 
    else:
        print("less")

您的问题是,您只比较第一个( refl[0] )和第二个( refl[1] )元素。 一个简单的解决方法是:

def funcc(refl):
    for i in range(len(refl)) - 1:
        if (refl[i + 1]) >= (refl[i]):
            return False
    return True

然后按如下方式使用它:

refl = ["100", "99", "90", "80", "60", "50", "10"]
if funcc(refl):
    print("Monotone decreasing")
else:
    print("Not monotone decreasing")

您的变量refl是一个列表,您可以使用 integer 索引来引用列表中的每个项目。 您可以使用这些索引来比较值,并使用 while 循环自动比较每对项目。 为此,您首先需要配置循环以访问列表中的每一项,在最后一项之前停止一项,因为您将提前比较一项。

refl = ["100", "99", "90", "80", "60", "50", "10"]
counter = 0
while counter < len(refl)-1: #remember, the length of the list is 7, the last index is 6
    if refl[counter] < refl[counter+1]: #if the item smaller than the next item
        print("The previous item is not larger")
    else:
        print("the previous item is larger")
    counter += 1 #add one to counter and re-assign

如果比较的是 integer,则需要先将所有项目转换为 integer。

refl = list(map(int, refl))

然后,逻辑AND all 用于比较greater前 n-1 项与最后 n-1 项。

result = all(map(int.__gt__, refl[:-1], refl[1:]))

refl = [“100”、“99”、“90”、“80”、“60”、“50”、“10”]

def procedure(refl): 
    for count in range(len(ref1)):
        if (refl[count]) > (refl[count+1]): 
            print("more") 
        else: 
            print("less")
procedure(ref1)

len(ref1) 将重复循环 n 次,其中 n 是 # #the list 中的项目数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM