首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使添加到数字列表中的数字适用于单词列表的索引,而不跳过任何数字。

如何使添加到数字列表中的数字适用于单词列表的索引,而不跳过任何数字。
EN

Stack Overflow用户
提问于 2017-01-27 19:44:52
回答 2查看 61关注 0票数 0

这是一个程序,将单词(文本)列表中的数字添加到数字列表(称为数字)中,以表示原始文本的索引,例如,“水手出海看他能看到什么,但他所能看到的只有深海海底”这句话应该返回为"1 2 3 4 5 5 4 4 6 6 7 9 6 6 6 11 12 9 6 6 6 13 1 14 15 17 5 5 5“,但返回为"1 2 3 4 4”。5 5 5 4 9 10 11 12 9 9 13 14 15 12 9 9 16 1 17 18 19 20 5 5引起麻烦。

这是计划的一部分,也是问题所在:

代码语言:javascript
运行
复制
for position, item in enumerate(text):
    if text.count(item) < 2:
        numbers.append(max(numbers) + 1)
    else:
        numbers.append(text.index(item) + 1)

“数字”和“文本”都是列表。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-01-27 20:20:47

一个简单的解决方案是在没有重复的情况下获得文本的创建版本,但保持相同的顺序,并使用index()从原始文本中查找单词的索引。

通过按空格拆分从字符串中创建列表:

代码语言:javascript
运行
复制
text="the sailor went to sea sea sea to see what he could see see see but all that he could see see see was the bottom of the deep blue sea sea sea"
listText=text.split(" ")

创建不包含文本中所有单词的重复项的新列表,使用count()检查word之前没有出现:

代码语言:javascript
运行
复制
unique_text=[listText[x] for x in range(len(listText))if listText[:x].count(listText[x])<1]

使用列表理解来获取listText中unique_text中每个单词的索引(并添加1):

代码语言:javascript
运行
复制
positions=[unique_text.index(x)+1 for x in listText]

最终代码:

代码语言:javascript
运行
复制
text="the sailor went to sea sea sea to see what he could see see see but all that he could see see see was the bottom of the deep blue sea sea sea"
listText=text.split(" ")
unique_text=[listText[x] for x in range(len(listText))if listText[:x].count(listText[x])<1]
positions=[unique_text.index(x)+1 for x in listText]

输出:

代码语言:javascript
运行
复制
[1, 2, 3, 4, 5, 5, 5, 4, 6, 7, 8, 9, 6, 6, 6, 10, 11, 12, 8, 9, 6, 6, 6, 13, 1, 14, 15, 1, 16, 17, 5, 5, 5]
票数 0
EN

Stack Overflow用户

发布于 2017-01-27 19:55:22

有字典的解决方案:

代码语言:javascript
运行
复制
text="the sailor went to sea sea sea to see what he could see see see but all that he could see see see was the bottom of the deep blue sea sea sea" 
l=text.split(' ')
d=dict()
cnt=0
for word in l :
    if word not in d : 
       cnt+=1
       d[word]=cnt 
out=[d[w] for w in l]  

#[1, 2, 3, 4, 5, 5, 5, 4, 6, 7, 8, 9, 6, 6, 6, 10, 11, 12, 8, 9, 6, 6, 6, 13, 1, 14, 15, 1, 16, 17, 5, 5, 5]  
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41901854

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档