【问题标题】:How to change a string input by the user into a dictionary with a key and value如何将用户输入的字符串更改为具有键和值的字典
【发布时间】:2016-08-19 04:57:14
【问题描述】:
sentence = input ("give sentence")    
user input = HELLO I LOVE PYTHON

我想把给定的句子改成格式,带变量sentence_dict

{1:HELLO, 2:I, 3:LOVE, 4:PYTHON}

【问题讨论】:

  • 感谢您的帮助

标签: python string dictionary sentence


【解决方案1】:

使用split()方法获取sentence中的单词列表:

words = sentence.split()

然后使用enumerate 内置函数构造一个生成器,将升序数字与列表中的单词相关联。默认情况下,enumerate 从 0 开始编号,但您希望它从 1 开始,因此将该值作为第二个参数传递:

numbered_words = enumerate(words, 1)

然后使用dict 内置函数从该生成器的输出构造一个字典。幸运的是,生成器以与您尝试构建的格式匹配的格式发出其 (number, word) 元组——dict 通过使用元组中的第一项作为键,第二项作为值来构造字典:

sentence_dict = dict(numbered_words)

如果你想简洁,你可以把所有的东西都塞进一行:

sentence_dict = dict(enumerate(sentence.split(), 1))

enumerate 生成器是唯一棘手的部分。 enumeratexrange 相似,因为它不返回序列,而是返回一个可以从中提取序列的对象。为了演示那里发生了什么,您可以使用for 循环从enumerate 生成器中提取(数字,单词)对并打印它们:

for num, word in enumerate(['a', 'b', 'c', 'd'], 57):
    print 'num is', num, 'and word is', word

这表明了这一点:

num is 57 and word is a
num is 58 and word is b
num is 59 and word is c
num is 60 and word is d

【讨论】:

  • 感谢您的帮助
猜你喜欢
  • 1970-01-01
  • 2014-12-27
  • 2019-07-17
  • 1970-01-01
  • 2021-10-13
  • 2023-02-21
  • 1970-01-01
  • 2020-08-07
  • 1970-01-01
相关资源
最近更新 更多