在列表中打印重复单词的位置

时间:2016-05-08 17:00:23

标签: python python-2.7

我需要在一个句子中找到单词的位置。但如果句子中有重复的单词,它将打印单词首次出现的位置。例如,我希望程序执行以下操作:

sentence = 'Ask Not What Your Country Can Do For You Ask What You Can Do For Your Country'

recurringword = ['Ask', 'Not', 'What', 'Your', 'Country', 'Can', 'Do', 'For', 'You']

pos = [0, 1, 2, 3, 4, 5, 6, 7, 8, 0, 2, 8, 5, 6, 7, 3, 4]

我的代码:

sentence = 'Ask Not What Your Country Can Do For You Ask What You Can Do For Your Country'

print sentence
words_into_list = sentence.split(" ")

recurring_word = 'Ask'

word = ""
word_list=[]


for i in range(len(words_into_list)):
if words_into_list[i] in word_list:

    print "Not A Unique Word"
else:
    word_list.append(words_into_list[i])
print word_list

1 个答案:

答案 0 :(得分:0)

您可以遍历句子中的每个单词,找到该单词第一次出现的位置:

sentence = 'Ask Not What Your Country Can Do For You Ask What You Can Do For Your Country'

words = sentence.split(" ")

[(i for i,v in enumerate(words) if (v == word)).next() for word in words]
# => [0, 1, 2, 3, 4, 5, 6, 7, 8, 0, 2, 8, 5, 6, 7, 3, 4]

快速解释:

外部循环用于理解,遍历列表中的每个单词:

[... for word in words]

内循环提取列表中与给定字符串匹配的索引单词,然后使用next抓取第一次出现的索引。

(i for i,v in enumerate(words) if (v == word)).next()

当我们将它们组合在一起时,我们得到嵌套循环,遍历列表中的每个单词,并为每个单词提取其第一次出现的位置。

此外,没有必要找到反复出现的单词来解决这个问题,但如果有必要的话:

recurring_words = set([word for word in words if words.count(word) > 1])