简体   繁体   中英

How to make 'a new list of tuple pairs' from 'a list of tuple pairs' with the most frequent tuples?

lst = [('wish', 'NOUN'), ('wish', 'VERB'), ('this', 'DET'), ('this', 'DET'), ('this', 'PROPN'), ('Christmas', 'PROPN')]

word_l = ['this', 'wish', 'Christmas']

The programs should find the words of 'word_l' in 'lst'. It should make a new list from the list of tuples 'lst' with the most frequent tuple based on those words. The new_list should contain,

new_list = [('wish', 'NOUN'), ('this', 'DET'), ('Christmas', 'PROPN')]

In the case where "wish" appears with "NOUN" once and with 'VERB' once, selecting any of them is fine. "this" should appear only with "DET". 'lst' is a long list of tuples like this.

I think this is what you are wanting

lst = [('wish', 'NOUN'), ('wish', 'VERB'), ('this', 'DET'), ('this', 'DET'), ('this', 'PROPN'), ('Christmas', 'PROPN')]
word_l = ['this', 'wish', 'Christmas']
dict = {}
new_l =[]
def main():
    for x in lst:
        if not x in dict:
            dict[x]=1
        else:
            dict[x] += 1
    n=0
    p = ()
    for w in word_l:
        for key in dict:
            if key[0]==w and dict.get(key)>n:
                p = key
                n = dict.get(key)
        
        new_l.append(p)
        n=0
        p=()
    print(new_l)
    
main()

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