【问题标题】:Indexes of a list Python列表 Python 的索引
【发布时间】:2017-01-20 10:16:35
【问题描述】:

我正在尝试查找如何在 Python 列表中打印单词的索引。如果句子是“Hello world world hello name”)我希望它打印列表“1、2、2、1、3”)

我删除了所有重复的单词:

sentence = input("Enter").lower()
words = sentence.split()
counts = []
for word in words:
    if word not in counts:
       counts.append(word)
print(counts)

但我仍然需要使用数组获取句子的索引

【问题讨论】:

标签: python


【解决方案1】:

如果您希望索引是“我在句子中看到的第 n 个唯一单词”,那么此代码将生成:

sentence = "Hello world world hello name".lower()
first_occurence = dict()
for pos, word in enumerate(sentence.split(" ")):
    if word not in first_occurence:
        first_occurence[word] = len(first_occurence)

res = [first_occurence[word] + 1 for word in sentence.split(' ')]

结果:[1, 2, 2, 1, 3]

【讨论】:

    猜你喜欢
    • 2017-10-04
    • 2019-07-05
    • 2018-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-05
    相关资源
    最近更新 更多