[英]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.