2014-02-21 30 views
1

我有一個問題,我需要解決這個問題,對於大多數人來說可能相當容易,但對我來說已證明對我來說有點困難之前沒有做過這種比較。以下是我正在解析的XML文件的一部分。我得到了一個字符串列表(NAME的文本),我想確定一些事情。首先,我想看看我回來的名字是否是唯一的。其次,我想知道是否有重複的名稱(同名,但不同的情況)。解決這個問題的最好方法是什麼?我不希望這份名單太大。這是我的XML代碼段和當前代碼:如何使用Python測試唯一字符串和重複字符串(不同情況)使用Python

<actions> 
     <action> 
      <name>Action_1</name> 
     </action> 
    <action> 
      <name>action_1</name> 
     </action> 
     <action> 
      <name>Action_2</name> 
     </action> 
    <action> 
      <name>ACTION_2</name> 
     </action> 
    </actions> 

    action = elementTree.findall('./actions/action') 
    nameList = [] 

    # Get the list of actions and stuff them in a list for further comparison. 
     for a in action: 
      for child in a: 
       if child.tag == 'name': 
        nameList.append(child.text) 
        print child.text 

輸出如下:

Action_1 
action_1 
Action_2 
ACTION_2 

所以,再一次,我只需要確定,如果我回來的字符串(name.text)是唯一或不。其次,我想知道是否有重複的名稱(同名,但不同的情況)。

回答

2
from collections import defaultdict, Counter 
d1 = Counter() 
d2 = defaultdict(set) 
# count appearence of entries 
for x in nameList: 
    d1[x] += 1 
    d2[x.lower()].add(x) 

# dupes are 
for k,v in d1.iteritems(): 
    if v>1: print k 

# different appearance of name 
for k,v in d2.iteritems(): 
    if len(v) > 1: print k 

如果你有一個很長... ...列表,看看布隆過濾器。

+0

非常好的例子,謝謝。它很棒!我選擇整體使用這一個。 – user2643864

2

如果您的名單不區分大小寫,請存儲它的.lower()。然後你就可以很容易地使用in來測試列表成員:

if child.tag == 'name': 
    text_lower = child.text.lower() 
    if text_lower in nameList: 
     print 'dupe!' 
    else: 
     nameList.append(text_lower) 
    print child.text 
+0

這也行得通。感謝您的明確解釋。 – user2643864

1
list_names = ['Action_1', 'action_1', 'Action_2', 'ACTION_2'] 

list_names = [name.lower() for name in list_names] 

name_counts = dict((name, list_names.count(name)) for name in set(list_names)) 

和name_counts回報:

{'action_2': 2, 'action_1': 2} 

或者,你可以使用collections.Counter,在Python 2.7前鋒可用。

import collections 
name_counts = collections.Counter(list_names) 

而且name_counts返回一個計數器對象,這是字典的一個子類:

Counter({'action_1': 2, 'action_2': 2}) 
+0

我喜歡使用計數器。效果很好。 – user2643864

相關問題