2014-01-27 32 views
0

大概這個笑話,但不知何故我無法解決這個問題。我從我想從每兩個元素剝離一些字符,使列表的另一個列表我有一個Python列表中的列表,我想從每兩個元素中去掉一些字符

list = [['A*68:02:01:03', 'A*33:01:01', '1'], 
     ['A*68:02:01:02', 'A*33:01:01', '1'], 
     ['A*68:02:01:01', 'A*33:01:01', '1']] 

required output = [['A*68:02', 'A*33:01', '1'], 
        ['A*68:02', 'A*33:01', '1'], 
        ['A*68:02', 'A*33:01', '1']] 

最後,我只想打印獨特的元素列表清單。如上面的情況下,所有三個元素是相同的,所以輸出應該是:

output = ['A*68:02', 'A*33:01', '1'] 

感謝您的幫助

+0

對於獨特的列表式的東西,看看[sets](http://docs.python.org/2/library/sets.html)。 – nmichaels

回答

1

你可以做這樣的事情:

def prefix(string): 
    """ 
    Returns the prefix of a string, including all characters 
    up until the second colon. 
    """ 
    return ":".join(string.split(":", 2)[:2]) 

def unique(iterable): 
    """ 
    Returns the unique elements in iterable, maintaining the 
    elements' relative order. 
    """ 
    result = [] 
    seen = set() 
    for el in iterable: 
     if el not in seen: 
      seen.add(el) 
      result.append(el) 
    return result 

L = [ 
    ['A*68:02:01:03', 'A*33:01:01', '1'], 
    ['A*68:02:01:02', 'A*33:01:01', '1'], 
    ['A*68:02:01:01', 'A*33:01:01', '1'], 
] 
prefixes = [(prefix(el[0]), prefix(el[1]), el[2]) for el in L] 

# The built-in class set accepts an iterable and returns a set, 
# an object with all duplicate elements removed. Since sets are 
# unordered, converting the set back to a list will likely 
# produce a list in which the original elements have lost their 
# relative order. 
# If this is a problem you can use the unique function from above. 
uniq = list(set(prefixes)) 

# If you really need a list of lists, instead of a list of tuples. 
uniq = [list(el) for el in uniq] 

我已經改名爲您輸入列表爲L,因爲命名爲list會隱藏內置函數列表。

2
>>> lst = [['A*68:02:01:03', 'A*33:01:01', '1'], ['A*68:02:01:02', 'A*33:01:01', '1'], ['A*68:02:01:01', 'A*33:01:01', '1']] 
>>> newLst = [tuple(':'.join(data.split(':', 2)[:2]) for data in sublist) for sublist in lst] 
>>> set(newLst) 
{('A*68:02', 'A*33:01', '1')} 

有趣的是':'.join(data.split(':', 2)[:2]。該分會將冒號分開data,只取前兩個部分並再次加入。這樣,我們在第二個冒號(包括那個)之後將所有東西都剝離。

其餘的只是一個列表理解通過嵌套列表。我們還需要將內部列表轉換爲元組,因此當我們調用set()時,它們是可散列的。這樣做會擺脫所有重複。

2

我想你想:

lst = [['A*68:02:01:03', 'A*33:01:01', '1'], 
     ['A*68:02:01:02', 'A*33:01:01', '1'], 
     ['A*68:02:01:01', 'A*33:01:01', '1']] 

output = [] 

for item in lst: 
    processed = [":".join(s.split(":")[:2]) for s in item] 
    if processed not in output: 
     output.append(processed) 

注意:不要叫自己的變量之類的東西list

相關問題