Home > Software engineering >  How to associate items of one list with items of another list with a condition in Python?
How to associate items of one list with items of another list with a condition in Python?

Time:09-17

I have two lists and I want to print the item of the first list and the item of the second list based on a condition. For instance, I want to print the languages associated with the use of proofing tools and the language associate with the use of translation tools. I don't know how to include the condition. How to print without repeating the same language? My code so far is below:

tools=['translation;proofing','proofing','translation', 'language learning;proofing']
languages=['catalan;English', 'italian', 'french, german', 'english, portuguese']
for i in range(len(tools)):
    for j in tools:
        if "proofing" in j:
            print(languages[i])

My output should be something like:

Proofing: catalan, English, italian, portuguese

Translation: catalan, English, french, german

CodePudding user response:

IIUC, try:

proofing = list()
translation = list()
for t, l in zip(tools, languages):
    if "proofing" in t:
        proofing.append(l)
    if "translation" in t:
        translation.append(l)

>>> proofing
['catalan;English', 'italian', 'english, portuguese']

>>> translation
['catalan;English', 'french, german']

If instead you mean you want to interpret the single list element "catalan;English" as two languages, try with set like so:

proofing = set()
translation = set()
for t, l in zip(tools, languages):
    components = [x.strip().capitalize() for x in l.replace(",", ";").split(";")]
    if "proofing" in t:
        proofing.update(components)
    if "translation" in t:
        translation.update(components)

>>> proofing
{'Catalan', 'English', 'Italian', 'Portuguese'}

>>> translation
{'Catalan', 'English', 'French', 'German'}
  • Related