简体   繁体   English

遍历List Python

[英]Iterate through List Python

I am trying to see if a string I have is similar to any of the strings in a dictionary in python. 我正在尝试查看我拥有的字符串是否类似于python词典中的任何字符串。 When I am looking for exact matches, I can do this: 当我寻找完全匹配时,我可以这样做:

stringList = []
if (myString in stringList):
    #do something

Looking for similar matches using Python Levenshtein is the best I can come up with (I'm sure with some errors). 使用Python Levenshtein寻找相似的匹配是我能想到的最好的方法(我敢肯定会有一些错误)。

stringList = []
for i in range(len(stringList)):
    if distance(myString, stringList[i]) < 2:
        #do something
    else:
        #do something else

Is there a better way? 有没有更好的办法? Thanks. 谢谢。

From https://stackoverflow.com/a/10018734/4941367 https://stackoverflow.com/a/10018734/4941367

Use the difflib module. 使用difflib模块。

difflib.get_close_matches(myString, myList)

it's more pythonic like this : 像这样更pythonic:

stringList = []
for item in stringList:
    if distance(myString, item) < 2:
        #do something
    else:
        #do something else

best regard 最良好的问候

If you don't care what string is close enough, you can use the min function: 如果您不在乎什么字符串足够接近,可以使用min函数:

if min(distance(x, myString) for x in stringList) < 2:
    # do something

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM