简体   繁体   中英

How to split list of strings using other lists?

v1 = ['Elisa', 'Liza', 'Izabela', 'Elisabeth', 'Lisa']
v11 = ['Carmine', 'Crimson', 'Madder']
v12 = ['Foxtrot', 'Romeo', 'Delta']

v2 = ['Abbey', 'Abbie', 'Abigail', 'Abby', 'Gail']
v21 = ['Orchid', 'Thistle', 'Mauve', 'Carmine']
v22 = ['Alpha', 'Romeo', 'Foxtrot']

v3 = ['Jonathan', 'Jon', 'John', 'Jonny', 'Johnny', 'Nathan']
v31 = ['Ultramarine','Midnight blue','Navy blue','Orchid']
v32 = ['India','Echo','Sierra']

vloc = ["USA", "Mexico", "Canada", "Greenland", "Panama", "Cuba", "Costa Rica"]

List 'a' has values one value appearing from v1, v2, and v3. Also it has any one value appearing from each of these lists - v11, v12, v21, v22, v31, and v32. But these values can be surrounded by other words.

v11 and v12 are dependent on presence of values from v1.

v21 and v22 are dependent on presence of values from v2.

v31 and v32 are dependent on presence of values from v3.

so if -

a = ["Abbie", "Carmine - Buffalo, New York, USA", "Foxtrot : XYZ LLC inc.", "Lisa", "Romeo: John Doe", "Carmine: ABC, Vancouver, British Columbia, Canada", "Jon", "Echo: Johnny Doe", "Orchid : Male"]

How to get expected output using above lists for say variables - a1, a2, a3, a1_vloc, and a2_vloc in the following manner:

print(a1)
>>> ["Lisa", "Romeo: John Doe", "Carmine: ABC, Vancouver, British Columbia, Canada"]

print(a2)
>>> ["Abbie", "Carmine - Buffalo, New York, USA", "Foxtrot : XYZ LLC inc."]

print(a3)
>>> ["Jon", "Echo: Johnny Doe", "Orchid : Male"]

print(a1_vloc)
>>> Canada

print(a2_vloc)
>>> USA

Short answer:

a1 = ["Lisa", "Romeo: John Doe", "Carmine: ABC, Vancouver, British Columbia, Canada"]

a2 = ["Abbie", "Carmine - Buffalo, New York, USA", "Foxtrot : XYZ LLC inc."]

vloc = ["USA", "Mexico", "Canada", "Greenland", "Panama", "Cuba", "Costa Rica"]

def check(haystack, needles):
    return [needle for needle in needles if any(needle in s for s in haystack)]

print(check(a1, vloc))  # prints ['Canada']

print(check(a2, vloc))  # prints ['USA']

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