【问题标题】:Remove repeated word in a list删除列表中的重复单词
【发布时间】:2016-04-23 13:51:11
【问题描述】:

我需要开发一个程序来接收用户输入的字符串,例如:

'to be or not to be'. 

然后将字符串分成单独的单词:

'to', 'be', 'or', 'not', 'to', 'be' 

然后将单词放入列表中:

['to', 'be', 'or', 'not', 'to', 'be'] 

但是,如果一个词被重复,则只计算该词的第一次使用并替换为它的位置编号。因此,例如,to be or not to be 中的 to 都将被计为 1。这是因为单词 to 重复出现,因此 to 的第一次出现占了这两个单词。将单词替换为其位置编号后,应使用这些编号重新创建句子。所以to be or not to be应该变成:

1, 2, 3, 4, 1, 2 

单词和数字列表应保存为单独的文件或单个文件。 到目前为止,这就是我所拥有的:

UserSentence = input('Enter your chosen sentence: ') #this is where the user inputs their sentence
UserSentence = UserSentence.split()#.split()takes the inputted string and breaks it down into individual words...
                               #... and turns it into a list
List1 = UserSentence
List2 = UserSentence

【问题讨论】:

  • 在我看来,这不足以证明提出这样的要求。
  • 我已经弄清楚如何从列表中删除重复的单词
  • 你需要证明你已经努力解决这个问题......
  • 我已经这样做了好几天了
  • 从阅读文档开始怎么样?比如,list 上有哪些方法可用?

标签: python python-3.x


【解决方案1】:

您将采取的方法是首先获得输入,就像您所做的那样。之后你会像你一样分裂。然后你会想要遍历每个单词,并在另一个列表中使用列表的索引方法附加位置。这将使您第一次出现每个单词,并且您想要添加 1 以便以您想要的方式获得单词的位置。这是一个示例代码。请理解并提出您对此的任何问题。

sentence = input("Enter a sentence: ")
words = sentence.split()

position = []
for word in words:
    position.append(words.index(word) + 1)

print(position)

这里是示例输出:

>>> Enter a sentence: to be or not to be
>>> [1, 2, 3, 4, 1, 2]

希望这会有所帮助。

【讨论】:

  • 我试图理解同样的事情。我猜是因为问的人没有提供他的任何代码?我的意思是他确实提供了前几个步骤。他只是不明白如何使用一些基本的内置功能。这就是网站的用途。
  • 我投了反对票 - 我不喜欢鼓励提问者拆分字符串然后转向 Stack Overflow。
  • 可能是因为多余的index() 调用和结果中的一个错误。现在可能是因为不必要的图像可能是文本。
  • @DonkeyKong。残酷。
【解决方案2】:

在 Python 2.7 上 sentence = input("请输入一个句子:") 会报错。 只需将输入替换为 raw_input

以上代码是简洁编码的可靠示例。

嗨,里迪克, 仅供参考, 下面的代码将保留订单并从单词列表中删除重复项。如果你想修改用户的输入然后做你的索引活动,

独特_1 = [] [unique_1.append(item) for item in words if item not in unique_1]

希望对你有帮助,

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-18
    • 2019-11-13
    • 1970-01-01
    • 1970-01-01
    • 2021-11-18
    相关资源
    最近更新 更多