Python:比较几千个字符串。有没有比较快的选择?

标签 python string performance comparison string-comparison

我有一组大约 6000 个数据包,出于比较目的,我将其表示为字符串(前 28 个字节)以与同样多的数据包进行比较,我也表示为 28 个字节的字符串。

我必须将一组中的每个数据包与其他所有数据包进行匹配。 匹配总是唯一

我发现比较字符串需要一点时间。有什么方法可以加快这个过程吗?

编辑 1:我不想排列字符串元素,因为我总是确保数据包列表和相应字符串列表之间的排序被保留

EDIT2:这是我的实现:

list1, list2 # list of packets (no duplicates present in each list!)
listOfStrings1, listOfStrings2 # corresponding list of strings. Ordering is preserved.
alreadyMatchedlist2Indices = []
for list1Index in xrange(len(listOfStrings1)):
            stringToMatch = listOfStrings1[list1Index]
            matchinglist2Indices = [i for i, list2Str in enumerate(listOfStrings2)
                                if list2Str == stringToMatch and i not in alreadyMatchedlist2Indices]
            if not matchinglist2Indices:
                tmpUnmatched.append(list1Index)
            elif len(matchinglist2Indices) == 1:
                tmpMatched.append([list1Index, matchinglist2Indices[0]])
                alreadyMatchedlist2Indices.append(matchinglist2Indices[0])
            else:
                list2Index = matchinglist2Indices[0] #taking first matching element anyway
                tmpMatched.append([list1Index, list2Index])
                alreadyMatchedlist2Indices.append(list2Index)

最佳答案

---这里我假设你正在一个一个地获取每个字符串并与所有其他字符串进行比较。---

我建议对您的字符串列表进行排序并比较相邻的字符串。这应该有 O(nlogn) 的运行时间。

关于Python:比较几千个字符串。有没有比较快的选择?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16068703/

相关文章:

java - 将 Map<String,String> 转换为 Map<String,Object>

c# - 阵列克隆访问?

performance - 为什么要从 Node.JS 的 sqlite block 中获取数据?

python - sqlalchemy:将 html 表插入 mysql 数据库

c++ - 在类中设置 Arduino 字符串值

德尔菲字符串: Pull a last name from a full name

database - 做或不做:将图像存储在数据库中

python - Scrapy - 通过动态添加 allowed_urls 来克服 start_uri 重定向 - parse_start_url 问题

java - ANTLR4 中 Python 解释器的缩进管理

python - 使用pygame和python跟随玩家的相机