2013-11-01 309 views
2

嗨,大家好我有多個字符串列表。 F.e:Python在循環中獲取名稱

params = { 
    "str1":"A Teststring which tests.", 
    "str2":"Strings are awesome to test", 
    "str3":"Teststring is a string that tests ", 
    "str4":"String awesome test tests" 
    } 


erg =[] 
allstrings = ['str1','str2','str3','str4'] 
userkeywords = ['teststring','awesome','test','string'] 
for str in allstrings: 
    strkeywords = params[str].split() 
    common = list(set(userkeywords) & set(strkeywords)) 
    howmuch = len(common) 
    erg.append(howmuch) 
print erg 

有了這個代碼,我得到的PARAMS字符串多萬字怎麼都是一樣的。 但是我怎樣才能打印出與用戶關鍵字共有最多字的字符串。

後市展望:

str1 : 4 
str2: 3 
str4: 3 

(號碼均爲示例)

任何人都可以幫助嗎?

回答

0

使用不同的數據結構erg,即一個dict

erg = {} 
allstrings = ['str1','str2','str3','str4'] 
userkeywords = set(['teststring','awesome','test','string']) 
for strs in allstrings: 
    strkeywords = params[strs].split() 
    #len() works on sets too, no need to convert this to a list 
    common = len(userkeywords & set(strkeywords)) 
    erg[str] = common 

for k in sorted(erg, key=erg.get, reverse=True): 
    print k, ':', erg[k] 

輸出:

str2 : 2 
str4 : 2 
str3 : 1 
str1 : 0 
+0

謝謝你們都可以完美運行。我怎樣才能打印f.e.只有3個最好的價值?因此,它只會在此示例中打印str2 str4和str3 – CloudySi

+0

@ user1477042是的,您可以使用slicing:'sorted(erg,key = erg.get,reverse = True)[:3]' –