在Python中附加For循环的主题索引

时间:2016-03-30 14:45:53

标签: python arrays for-loop indices

所以我制作一个程序,将句子重写为句子中所有独特单词的索引(例如句子"快速棕狐狐狸"将被重写为&#34 ; 12323&#34)。这是我到目前为止所得到的;

sentence=input("please input your sentence")
sentence=sentence.split(" ")
unique=[]
positions=[]
print(sentence)
for i in sentence:
    if i in (unique):
        print(" the item " + i + " has been repeated")
        ind = i.index(i)
        positions.append(ind)
    else:
        unique.append(i)
print(unique)
print(positions)  

我想获得" i"的索引并将其附加到列表" position&#34 ;,但是当我用句子"快速棕狐狐狸"运行上面的代码时我得到了#34;位置&#34 ;;

[0, 0]

我想要的输出看起来更像这样;

[2, 3]

这似乎是一个简单的问题,但对于我的生活,我无法弄明白。内置"枚举"功能并不适合问题,因为它使得#34; i"将永远不会被发现" unique"因此"职位"会是空的。

2 个答案:

答案 0 :(得分:0)

更改i.index(i) sentence.index(i)会修复您的代码:

sentence="quick brown fox brown fox" #input("please input your sentence")
sentence=sentence.split(" ")
unique=[]
positions=[]
print(sentence)
for i in sentence:
    if i in (unique):
        print(" the item " + i + " has been repeated")
        ind = sentence.index(i)
        positions.append(ind)
    else:
        unique.append(i)
print(unique)
print(positions) 

注意输出是[1,2]而不是你想要的[2,3],因为从0开始数组的python约定。如果你想要[2,3]作为答案你可以简单地设置{{ 1}}

答案 1 :(得分:0)

好的,感谢您的所有贡献,但我找到了一个非常简单的解决方案:

sentence = input("Please input your sentence: ")
sentence = sentence.slpit(" ")

for i in sentence:
    print(sentence.index(i)+1)

句子的输出"快速棕狐狐狸"是:

1
2
3
2
3

这正是我所需要的。