简体   繁体   English

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

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

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

The above stores the individual words in the input into a list.以上将输入中的单个单词存储到列表中。 But now how do I replace each word in Sentence with the position of that word?但是现在我如何用那个词的位置替换Sentence每个词?

Map the string to its index using the map and index function.使用 map 和 index 函数将字符串映射到其索引。

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

You may also do:你也可以这样做:

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

or或者

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

or或者

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.

相关问题 从列表中的特定位置打印单词,每个单词都有后缀 - Print words from specific position in a list with suffix to each word 如果它在单词列表中,则替换字符串中的单词 - Replace a word in a string if it is in a list of words 打印一个字符串,该字符串是通过根据单词的位置获取单词列表中的每个连续字母而形成的? - Printing a string which is formed by taking each successive letter in the list of words based on the position of the word? 打印并查找单词和单词在列表中的位置 - Print and Find The Position Of A Word And Words In A List 如果字符串中的单词属于 pandas 中的单词列表,则替换它 - Replace a word in a string if it belongs to a list of words in pandas 试图用列表中出现的位置替换列表中的单词 - trying to replace words in a list with the position it comes in, in the sentence 将单词列表中的所有单词替换为python中的另一个单词 - Replace all words from word list with another string in python 用列表中的单词替换句子中的单词并复制列中的新句子 - Replace a word in a sentence with words from a list and copying the new sentences in a column 如何将每个单词映射到在python中跟随它的单词列表? - how to dict map each word to list of words which follow it in python? 将列表中的单词分配给字符串,每个单词之间有空格 - assigning words from a list to a string with spaces between each word
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM