简体   繁体   English

通过值遍历许多列表

[英]Iterate by value over many lists

I have a bunch of interables (whose entries represent positions on genomes) that are sorted. 我有一堆被排序的互作式(其条目代表基因组上的位置)。 I would like to process them simultaneously such that all of them that have data at a particular position are processed, whereas those that do not are skipped. 我想同时处理它们,以便处理所有在特定位置具有数据的数据,而忽略不包含数据的数据。

A rather clunky solution is 一个比较笨拙的解决方案是

import sys
it1 = iter([0, 1, 3, 5])    
it2 = iter([0, 2, 4, 5])    
it3 = iter([3, 5, 7])    
def do_stuff(objects, values):                                              
    print("iterables [%s] have value %s"  % (objects, values[0]))           

def iterate_many(iterables):                                                
    cur_ele = [next(i) for i in iterables]                                  
    is_finished = [False for i in iterables]                                
    while not all(is_finished):                                             
        lowest_val = min(cur_ele)                                           
        lowest_obj = [e for e in cur_ele if e == lowest_val]                
        to_increment = [i for i, e in enumerate(cur_ele) if e == lowest_val 
            and not is_finished[i]]                                         
        yield do_stuff(to_increment, lowest_obj)                            
        for i in to_increment:                                              
            try:                                                            
                cur_ele[i] = next(iterables[i])                             
            except StopIteration:                                           
                is_finished[i] = True                                       
                cur_ele[i] = sys.maxsize                                    

which results in 导致

In [76]: for i in iterate_many( [it1, it2, it3]): pass
iterables [[0, 1]] have value 0                       
iterables [[0]] have value 1                          
iterables [[1]] have value 2                          
iterables [[0, 2]] have value 3                       
iterables [[1]] have value 4                          
iterables [[0, 1, 2]] have value 5                    
iterables [[2]] have value 7                          

Is there an easier/ more pythonic way of accomplishing this goal? 有没有更简单/更Python化的方式来实现这一目标?

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

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