![](/img/trans.png)
[英]compare elements of list to elements of list of lists and conditionally create new lists
[英]Conditionally create list of lists
我不知道我是否以最好的方式措辭,但實際上我想根據不同的條件創建一個列表列表。
我使用ElementTree讀取了一些XML數據,並對其進行了解析,然后遍歷樹並將所有標簽放入稱為tags
的列表中,並將其值放入名為vals
的列表中。
在我的標簽列表中,有幾個句子標簽供我用作字典的鍵,並將相應的值附加到列表中並制成值。
我的標簽列表,它們的對應值和句子標簽如下所示。
tags = ['irrel', 'TAG_ONE', 'TAG_ONE', 'TAG_TWO', 'TAG_ONE', 'TAG_TWO', 'irrel']
vals = ['not_rel', 1, 2, 5, 3, 6, 'not_rel']
sent_tags = ['TAG_ONE', 'TAG_TWO']
我理想的輸出是使用以下代碼實現的tags_dict = {'TAG_ONE': [1, 2, 3], 'TAG_TWO': [5, 6]}
。
sent_vals = list()
# Make a list of all TAG_ONE values and append list to sentence values list
tag_one = list()
tag_one_locs = [i for i, x in enumerate(tags) if x == 'TAG_ONE']
for t in tag_one_locs:
tag_one.append(vals[t])
sent_vals.append(tag_one)
# make a list of all TAG_TWO values and append list to sentence values list
tag_two = list()
tag_two_locs = [i for i, x in enumerate(tags) if x == 'TAG_TWO']
for tt in tag_two_locs:
tag_two.append(vals[tt])
sent_vals.append(tag_two)
tags_dict = dict(zip(sent_tags, sent_vals))
但是,這相當丑陋,僅復制和粘貼代碼一百萬次是不切實際的,因為我的真實數據有大約70個句子標簽。 我在如何將代碼簡化為某種列表理解(或其他方式)方面處於空白。
好吧,您可以使用collections.defaultdict(list)
大大簡化該過程
像這樣:
import collections
tags = ['irrel', 'TAG_ONE', 'TAG_ONE', 'TAG_TWO', 'TAG_ONE', 'TAG_TWO', 'irrel']
vals = ['not_rel', 1, 2, 5, 3, 6, 'not_rel']
sent_tags = {'TAG_ONE', 'TAG_TWO'} # set is preferred when a lot of elements (faster "in" lookup)
tags_dict = collections.defaultdict(list)
for tag,val in zip(tags,vals):
if tag in sent_tags:
tags_dict[tag].append(val)
print(dict(tags_dict)) # convert to dict just to print
結果:
{'TAG_TWO': [5, 6], 'TAG_ONE': [1, 2, 3]})
字典理解:
{sent_tag: [vals[ind] for ind, tag in enumerate(tags) if tags[ind] == sent_tag] for sent_tag in sent_tags}
如果理解結構讓您感到困惑,請考慮以下代碼:
output = {}
for sent_tag in sent_tags:
val_list = []
for ind, tag in enumerate(tags):
if tags[ind] == sent_tag:
val_list.append(vals[ind])
output.update({sent_tag: val_list})
無論哪種方式:
您的輸出將是:
{'TAG_ONE': [1, 2, 3], 'TAG_TWO': [5, 6]}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.