简体   繁体   中英

create a dict for items of two list once co occur in the same line in a file text

If there are two lists of items, and the task is to create a dict of the items of the two lists (one items from list1 as key and one from list2 as value) once the two items co-occure in the same line of file text. Is there another way different from my following trial? Thanks

di =  {}
for line in file_text:
    for x in list1:
        for y in list2:
            if x in line and y in line:
                di[x]=y   

For best performance results, you should use itertools.izip along with Python's dict comprehension syntax :

import itertools
di = {k: v for line in file_text for k, v in itertools.izip(list1, list2) if k in line and v in line}

A dict comprehension is a faster alternative to create your dictionary than nested for loops, and itertools.izip is more economical for memory consumption than a simple zip (especially for larger lists).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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