繁体   English   中英

用每个单词的位置替换列表中的单词

[英]Replace the words in a list with the position of each word

Sentence = input("type in sentence:").split()

以上将输入中的单个单词存储到列表中。 但是现在我如何用那个词的位置替换Sentence每个词?

使用 map 和 index 函数将字符串映射到其索引。

Sentence = str(input("Type in the sentence here:")).split(" ")
indexed_sentence = list(map(lambda x: Sentence.index(x), Sentence))

你也可以这样做:

indexed_sentence = [Sentence.index(x) for x in Sentence]

或者

indexed_sentence = []
for x in Sentence:
    indexed_sentence.append(Sentence.index(x))

或者

indexed_sentence = []
for x in Sentence:
    for count in range(len(Sentence)):
        if x == Sentence[count]:
            indexed_sentence.append(count + 1)
            break

只需这样做:

Sentence = [x for x in range(len(Sentence))]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM