如何提取列表中每个元组的“x”并以python方式连接?

2024-06-26 14:25:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我从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的方式来实现这一点?你知道吗

这就是我到目前为止所做的,我知道这是非常丑陋的。我是Python处女。你知道吗


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

print Y

Tags: infriendfornnbinghappynltkday
3条回答

使用list comprehension:

>>> 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']
Y = [' '.join(t[0] for t in l) for l in X]

使用zipstr.join可以很容易地完成。你知道吗

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

zip(*sequences)[i]是一种常见的Python习惯用法,用于从每个序列(列表、元组等)获取第i个值

它类似于[seq[i] for seq in sequences],但即使序列不可下标(例如迭代器),它也可以工作。在Cpython中,由于使用了一个内置的,它可能会稍微快一点(尽管如果它很重要的话,您应该总是对它进行分析)。而且,它返回一个元组而不是一个列表。你知道吗

有关详细信息,请参阅the documentation。你知道吗

相关问题 更多 >