【问题标题】:How do I use Enumerate to to make each word into a number not each character如何使用 Enumerate 将每个单词变成一个数字而不是每个字符
【发布时间】:2017-04-09 19:36:33
【问题描述】:

所以我需要编写一个程序让用户输入一个句子,然后代码将该句子转换为与其在列表中的位置相对应的数字,我在这里看到命令 Enumerate:Python using enumerate inside list comprehension 但这得到每个字符不是每个单词,所以这是我目前的代码,谁能帮我解决这个问题?

list = []
lists = ""
sentence= input("Enter a sentence").lower()
print(sentence)
list.append(lists)
print(lists)
for i,j in enumerate(sentence):
    print (i,j)

【问题讨论】:

  • 不清楚你想在这里做什么。你能给出一些示例输入和预期输出吗?
  • enumerate(sentence.split())
  • 所以我只是简单地介绍一下它的作用,首先用户输入一个句子,然后程序打印这个句子并将单词转换为数字,但在它的位置在列表中,例如我输入“Hello world”,代码应该打印“1 2”

标签: python enumerate


【解决方案1】:

您的 sentence 是字符串,因此它被拆分为单个字符。您应该先将其拆分为单词:

for i,j in enumerate(sentence.split(' ')):

【讨论】:

    【解决方案2】:

    你也可以试试这个:

    >>> sentence = 'I like Moive'
    >>> sentence = sentence.lower()
    >>> sentence = sentence.split()
    >>> for i, j in enumerate(sentence):
    ...         print(i, j)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-25
      • 1970-01-01
      • 2013-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-13
      • 2010-10-29
      相关资源
      最近更新 更多