检查Python数组中的两个相同的字符串元素

时间:2012-01-05 07:32:03

标签: python arrays

我有一个字符串数组如下:

  

[A1,A2,A1,A3,A2]

我想找到相似的字符串并将它们放入一个新的数组中,如下所示:

  

[A1,A2]

我是Python新手。请告诉我如何做到这一点。

感谢。

4 个答案:

答案 0 :(得分:4)

如果用数组表示python中的列表 - :

s = ["a1","a2","a1","a3","a2"]
duplicates = [x for x in s if s.count(x) > 1]
myl = list(set(duplicates))
print myl

输出['a1', 'a2']

答案 1 :(得分:1)

使用collections.Counter

的替代解决方案
s = ["a1","a2","a1","a3","a2"]
c=collections.Counter(s)
print dict(c.most_common(len(c)-1)).keys()
['a1', 'a2']    

答案 2 :(得分:0)

这是 O(nlog(n))查找重复项的方法。初始列表已排序( O(nlog(n))),以便在相邻位置重复元素。然后简单的 O(n)迭代就可以找到重复项。

s = ["a1","a2","a1","a3","a2"]
s.sort() # sort changes initial list
new_list = []
prev = (None, False)
for x in s:
    if prev == (x, False):
        new_list.append(x)
        prev = (x, True)
    else:
        prev = (x, False)
print new_list

答案 3 :(得分:0)

虽然不知道性能 - 但它有效

s = ["a1","a2","a1","a3","a2"]
i=0
common=[]
for i in range(0,len(s)):
  if s[i] not in common and s[i] in s[i+1:]:
    common.append(s[i])