检查下一个值是否等于python循环中的当前值? [英] Check if next value is equal o current value in python loop?

查看:215
本文介绍了检查下一个值是否等于python循环中的当前值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在遍历文件,我想检查下一个即将到来的对象是否等于当前对象.这两个对象的属性名称都类似Obj.name

I am looping through a file and I want to check if the next coming object is equal to current object. Both the objects have a attribute name like Obj.name

这是一些简化的示例:

文件包含:

Oba_A
Obj_B
Obj_C
Obj_D

我正在像这样遍历他们

for obj in open("file.txt"):
    check if Obj_A.name==Obj_B.name, if not:
        if Obj_B.name==Obj_C.name

我是一名生物学家,正在学习编程.希望我能在这里得到足够的鼓励.

I am a biologist learning programming. I hope I get enough encouragement here.

推荐答案

忽略了如何从文本文件中获取对象的问题,您的基本答案可能看起来像这样:

Overlooking the issue of how you're getting objects from a text file, your basic answer could look something like this:

last_value = None
for obj in collection:
    if obj.name == last_value:
        # do something
    else:
        # do something different
    last_value = obj.name

更新: 如果要基于与下一个对象的匹配对第一个对象执行 操作,则可以存储对上一个对象的引用,而不仅仅是名称,例如:

Update: If you want to act on the first object based on a match with the next object, you could store a reference to previous object instead of just the name, ex:

prev_obj = None
for obj in collection:
    if obj.name == prev_obj.name:
        # do something with prev_obj
    else:
        # do something different
    prev_obj = obj

或者,如果真的有帮助将它们视为当前"和下一个":

Or, if it truly helps to think of these as "current" and "next":

cur_obj = None
for next_obj in collection:
    if next_obj.name == cur_obj.name:
        # do something with cur_obj
    else:
        # do something different
    cur_obj = next_obj

但是请注意,我所做的只是更改了命名.程序仍然相同.

But notice that all I've done is changed the naming. The procedure is still the same.

其他更新: 循环中的第一次,prev_obj为None,因此它没有name属性.通过将此案例更新为

Additional Update: The first time through the loop, prev_obj is None, so it won't have a name attribute. Trap that case by updating this to:

prev_obj = None
for obj in collection:
    if prev_obj is not None and obj.name == prev_obj.name:
        # do something with prev_obj
    else:
        # do something different
    prev_obj = obj

这篇关于检查下一个值是否等于python循环中的当前值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆