简体   繁体   中英

Python: Comparing strings in a list with two different list lengths

I have two lists containing strings with different lengths. Now I want to check if a string in one list is the substring of the other list to create a newlist with the same length as the string_list.

string_list = ['expensive phone', 'big house', 'shiny key', 'wooden door']
substring_list = ['phone','door']

What I have done so far

newlist=[]
for i in string_list:
    for j in substring_list:
        if i in j:
            newlist.append(j)
print newlist 

So it gives me

 newlist = ['phone', 'door']        

But what I am trying to achieve is a list as following

newlist = ['phone', '-', '-', 'door']

for loops can take an else block. You can use this else block to append the '-' in the case where the string is not found:

newlist=[]
for i in string_list:
    for j in substring_list:
        if j in i:
            newlist.append(j)
            break
    else:
        newlist.append('-')
print(newlist)
# ['phone', '-', '-', 'door']

If you want the result to be same length as the first list, you need to put a break in the if so that if the two items are contained in one of the strings (eg 'expensive phone door' ), you won't make two appends which will skew the resulting list length.

The break also ensures the else block of the for is not executed when an item has been found.

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