以字符串形式获取元组(在元组列表中)的第二个元素

2024-09-28 03:13:10 发布

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

我有一个输出是元组列表。看起来像这样:

annot1=[(402L, u"[It's very seldom that you're blessed to find your equal]"), 
        (415L, u'[He very seldom has them in this show or his movies]')…

我只需要使用元组的第二部分来应用“split”并分别获取句子中的每个单词。在

现在,我无法分离元组的第二部分(文本)。在

这是我的代码:

^{pr2}$

但我得到:

TypeError: sequence item 0: expected string, tuple found

我试图使用annot1[1],但它给了我文本的第二个索引,而不是元组的第二个元素。在


Tags: to文本reyou列表yourthatit
2条回答

annot1是元组的列表。要从每个元素中获取字符串,可以执行以下操作

def scope_match(annot1):
    for pair in annot1:
        string = pair[1]
        print string  # or whatever you want to do

您可以使用列表理解来执行以下操作:

annot1=[(402L, u"[It's very seldom that you're blessed to find your equal]"), 
        (415L, u'[He very seldom has them in this show or his movies]')]
print [a[1].strip('[]').encode('utf-8').split() for a in annot1]

输出:

^{pr2}$

可以这样计算annot1和annot2中相应位置上字符串的交集:

for x,y in zip(annot1,annot2):
    print set(x[1].strip('[]').encode('utf-8').split()).intersection(y[1].strip('[]').encode('utf-8').split())

相关问题 更多 >

    热门问题