gpt4 book ai didi

python - 如何保存字符串的顺序?(Python 3.)

转载 作者:太空宇宙 更新时间:2023-11-03 16:40:59 24 4
gpt4 key购买 nike

我需要保存字符串中单词的顺序,其中每个单词都用其第一次出现的索引(基于 1)进行标识。

对于示例输入

sentence = "i am what i am am"

期望的输出是

order = "1 2 3 1 2 2"

提前致谢。 :)

最佳答案

使用字典来跟踪单词首次出现的位置:

s = 'i am what i am am'
seen = {}
result = []
for index, word in enumerate(s.split(), 1):
result.append(seen.setdefault(word, index))
result = ' '.join(map(str, result))

print(result) # 1 2 3 1 2 2

关于python - 如何保存字符串的顺序?(Python 3.),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36790231/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com