簡體   English   中英

訪問元組列表中元組第一個元素的范圍

[英]Accessing a range of the first element of a tuple in a list of tuples

有點Python /編程新手。

我正在嘗試從元組列表中訪問指定范圍的元組,但是我只想訪問元組范圍中的第一個元素。 指定的范圍基於我正在由nltk標記和標記的文本字符串中尋找的模式。 我的代碼:

from nltk.tokenize import word_tokenize
from nltk.tag import pos_tag

text = "It is pretty good as far as driveway size is concerned, otherwise I would skip it"
tokenized = word_tokenize(text)
tagged = pos_tag(tokenized)

def find_phrase():
    counter = -1
    for tag in tagged:
        counter += 1
        if tag[0] == "as" and tagged[counter+6][0] == "concerned":
            print tagged[counter:counter+7]

find_phrase()

打印輸出:

[('as', 'IN'), ('far', 'RB'), ('as', 'IN'), ('driveway', 'NN'), ('size', 'NN'), ('is', 'VBZ'), ('concerned', 'VBN')]

我真正想要的是:

['as', 'far', 'as', 'driveway', 'size', 'is', 'concerned']

是否可以修改我的代碼行print tagged[counter:counter+7]以獲取所需的打印輸出?

可能最簡單的方法是使用列表理解 該語句從列表中每個元組的第一個元素創建一個列表:

print [tup[0] for tup in tagged[counter:counter+7]]

或者只是為了好玩,如果元組總是成對的,則可以將列表展平(使用您喜歡的任何方法),然后使用python的切片符號的步驟符號打印第二個元素:

print list(sum(tagged[counter:counter+7], ()))[::2]

或將mapitemgetter函數一起使用,該函數調用__getitem__()方法來檢索列表中每個元組的第0個索引:

from operator import itemgetter
print map(itemgetter(0), tagged[counter:counter+7])

還要別的嗎? 我敢肯定還有更多。

您可以這樣使用:

result, _ = zip(*find_phrase())
print result

您嘗試過拉鏈嗎? 還有名稱中的item [0]

暫無
暫無

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

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