2016-09-17 40 views
0

提取一組,我保持message_idmessage_writer_id一起在一個Python列表,像這樣:從複合元素列表在python

composite_items = ['1:2', '2:2', '3:2', '4:1', '5:19', '20:2', '45:1', ...] 

,每個元素都是message_id:message_poster_id

從上面的列表中,我想提取所有message_writer_idsset。即我想提取包含所有唯一編號一個set:讓我結束了:

item_set = ['2', '1', '19'] 

什麼是最有效的方式做到這一點在Python?


目前,我想我會做這樣的事情:

new_list = [] 
for item in composite_items: 
    element = item.split(":")[1] 
    new_list.append(element) 
new_set = set(new_list) 

想知道是否有實現這一目標更快的方法。

+4

更多consise,可能會稍快。讓我們將生成器理解傳遞給'set'的構造函數:'set(o.split(':')[1] for composite_items)' –

+0

公平的,這是一個改進。如果您將它作爲一個發佈,我會接受這個答案。 –

回答

2

您可以使用一套理解,像這樣:

new_set = {item.partition(":")[2] for item in composite_items} 

集理解快,不像str.split()str.partition()分裂一次,並停止尋找更多的冒號。與str.split(maxsplit=1)非常相似。

0
composite_items = ['1:2', '2:2', '3:2', '4:1', '5:19', '20:2', '45:1', ...] 
posters = dict() 
for element in composite_items: 
    poster_id = element.split(":")[1] 
    posters[poster_id] = posters.get(poster_id, 0) + 1 

您可以使用詞典並計算message_poster_id發送的郵件數量。 posters.get(poster_id,0) + 1檢查是否存在海報。如果存在,如果不存在其添加到poster_id詞典將其獲取其值(消息數)和1

增加它,並將它設置爲0。