我有一组大约 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/