python for loop, how to find next value(object)?

后端 未结 4 1044
Happy的楠姐
Happy的楠姐 2020-12-18 11:44

HI, I\'m trying to use for loop to find the difference between every two object by minus each other. So, how can I find the next value in a for loop?

for ent         


        
4条回答
  •  猫巷女王i
    2020-12-18 12:17

    zip works for lists, but for the general case:

    def pairs(it):
        it = iter(it)
        prev = next(it)
        for v in it:
            yield prev, v
            prev = v
    
    a = [1,2,3,4,5]
    for prev, cur in pairs(a):
        print cur - prev
    
    import itertools as it
    for prev, cur in pairs(it.cycle([1,2,3,4])):
        print cur - prev
    

    This works efficiently for large containers, and more importantly, it works for iterators:

    for prev, cur in pairs(open("/usr/share/dict/words").xreadlines()):
        print cur, prev,
    

    Edit: I changed the generator to omit the first value with no previous value, since that fits the original question better ("finding differences between adjacent pairs"), and I added an example case showing that it works for an infinitely-repeating iterator.

提交回复
热议问题