簡體   English   中英

如何在列表中提取每個元組的'x'並以python方式連接?

[英]How to extract 'x' of each tuple in a list and concatenate in python way?

我有一個這樣的值,我從NLTK樹中提取。


[[('Happy', 'NNP'), ('Mother', 'NNP')], [('Day', 'NNP')], [('Joey', 'NNP'), ('M.', 'NNP'), ('Bing', 'NNP')], [('kind', 'NN')], [('happy', 'JJ'), ('wife', 'NN')], [('mother', 'NN')], [('friend', 'NN')]]

我希望最終的結果是

['Happy Mother','Day','Joey M. Bing','kind','happy wife','mother','friend']

我怎么用python方式做到這一點?

這是我到目前為止所做的,我知道這非常難看。 我是一個蟒蛇處女。


Y = []
for x in X:
    s = ""
    for z in x:
        s += z[0] + " "
    Y.append(s)

print Y

你可以使用zipstr.join輕松str.join

result = [' '.join(zip(*row)[0]) for row in data]

zip(*sequences)[i]是一種常見的Python習慣用法,用於從每個序列中獲取第i個值(列表,元組等)

它類似於[seq[i] for seq in sequences]但即使序列不是可訂閱的(例如迭代器),它也可以工作。 在Cpython中,由於使用了內置函數,它可能會稍快一些(盡管如果它很重要,你應該總是進行分析)。 此外,它返回一個元組而不是列表。

有關更多信息,請參閱文檔

Y = [' '.join(t[0] for t in l) for l in X]

使用列表理解:

>>> X = [[('Happy', 'NNP'), ('Mother', 'NNP')], [('Day', 'NNP')], [('Joey', 'NNP'), ('M.', 'NNP'), ('Bing', 'NNP')], [('kind', 'NN')], [('happy', 'JJ'), ('wife', 'NN')], [('mother', 'NN')], [('friend', 'NN')]]
>>> Y = [' '.join(z[0] for z in x) for x in X]
>>> Y
['Happy Mother', 'Day', 'Joey M. Bing', 'kind', 'happy wife', 'mother', 'friend']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM