简体   繁体   English

反正有没有将此 for 循环转换为列表理解?

[英]Is there anyway to convert this for loop into list comprehension?

Basically I'm not sure if there is any possible way to convert this code into list comprehension.基本上我不确定是否有任何可能的方法可以将此代码转换为列表理解。 list1 and list3 are lists of lists that have been extracted from information about genes. list1 和 list3 是从基因信息中提取的列表列表。 So basically x[2] is a gene_id, and y[0] is also a gene_id.所以基本上x[2]是一个gene_id,y[0]也是一个gene_id。 y[1] is gene names. y[1] 是基因名称。 basically I want to end up with list 5, which is a lists of lists that I can loop through to write in a tsv.基本上我想以列表 5 结尾,这是我可以循环写入 tsv 的列表列表。

list2 = []

list4 = []

list5 = []

for x in list1:
    for y in list3:
        if x[2] == y[0]:
            list2.append(y[1])
    list4.append(x[2])
    list4.append(",".join(list2))
    list5.append(list4)
    list2 = []
    list4 = []

For a list in list1, x is [9606,HEX1M1,9606.ENSP00000328773].对于 list1 中的列表,x 是 [9606,HEX1M1,9606.ENSP00000328773]。

Then for all y that has y[0] == x[2] in list3, so for instance, [9606.ENSP00000395733,ZNF737-001,Ensembl_HGNC_trans_name Ensembl_Vega_transcript] and [9606.ENSP00000395733,ZNF737-002,Ensembl_HGNC_trans_name Ensembl_Vega_transcript]然后对于 list3 中具有 y[0] == x[2] 的所有 y,例如,[9606.ENSP00000395733,ZNF737-001,Ensembl_HGNC_trans_name Ensembl_Vega_transcript] 和 [9606.ENSP00000395733,ZNF737-002,Ensembl_HGNC_trans_name Ensembl_Vega]

Then we want to get [["9606.ENSP00000395733", "ZNF737-001, ZNF737-002,HEX1M1"]] for list 5 after that iteration.然后我们想在迭代后得到列表 5 的 [["9606.ENSP00000395733", "ZNF737-001, ZNF737-002,HEX1M1"]] 。

You can create a mapping dict from list3 that maps keys in the first items to lists of values in the second items, so that you can use a list comprehension to iterate over list1 to output lists of pairs of keys and associated lists from the aforementioned mapping dict for keys that are found in the dict:您可以从list3创建一个映射字典,将第一项中的键映射到第二项中的值列表,以便您可以使用列表推导将list1迭代到 output 键对列表和来自上述映射的关联列表字典中找到的键的字典:

mapping = {}
for k, v, *_ in list3:
    mapping.setdefault(k, []).append(v)
list5 = [[k, ','.join(mapping[k])] for *_, k in list1 if k in mapping]

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

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