简体   繁体   中英

How can i compare two lists of words, change the words that are in common, and print the result in python?

if i have a list of strings-

common = ['the','in','a','for','is']

and i have a sentence broken up into a list-

lst = ['the', 'man', 'is', 'in', 'the', 'barrel']

how can i compare the two,and if there are any words in common, then print the full string again as a title. I have part of it working but my end result prints out the newly changed in common strings as well as the original.

new_title = lst.pop(0).title()
for word in lst:
    for word2 in common:
        if word == word2:
            new_title = new_title + ' ' + word

    new_title = new_title + ' ' + word.title()

print(new_title)

output:

The Man is Is in In the The Barrel

so I'm trying to get it so that the lower case words in common, stay in the new sentence, without the originals, and without them changing into title case.

>>> new_title = ' '.join(w.title() if w not in common else w for w in lst)
>>> new_title = new_title[0].capitalize() + new_title[1:]
'The Man Is in the Barrel'

If all you're trying to do is to see whether any of the elements of lst appear in common , you can do

>>> common = ['the','in','a','for']
>>> lst = ['the', 'man', 'is', 'in', 'the', 'barrel']
>>> list(set(common).intersection(lst))
['the', 'in']

and just check to see whether the resulting list has any elements in it.

If you want the words in common to be lowercased and you want all of the other words to be uppercased, do something like this:

def title_case(words):
    common = {'the','in','a','for'}
    partial = ' '.join(word.title() if word not in common else word for word in words)
    return partial[0].capitalize() + partial[1:]

words = ['the', 'man', 'is', 'in', 'the', 'barrel']
title_case(words) # gives "The Man Is in the Barrel"

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