繁体   English   中英

Python 用户输入以列出分隔值

[英]Python User Input To List Separated Values

我一直在尝试创建一个脚本:

  • 要求用户输入关键字
  • 将用户的输入存储在列表中
  • 打印列表中的每个值

当我尝试打印列表时,所有值似乎都在索引0

inputwords = input('What keywords are you looking for?').split()
inputwordslist = []

inputwordslist.append(inputwords)
inputwordslist = enumerate(inputwordslist)
print (list(inputwordslist))

输出如下:

What keywords are you looking for?This is a test
[(0, ['This', 'is', 'a', 'test'])]

对于您的问题的最简单解决方案,@Chris_Rands 已经将其发布在您问题的评论中: .split()返回一个列表。 您不必为结果单独制作一个,只需枚举 split 函数返回的值即可:

inputwords = input('What keywords are you looking for?').split()
result = list(enumerate(inputwords))
print(result)

你在找什么关键词? 这是一个单词列表。
[(0, 'This'), (1, 'is'), (2, 'a'), (3, 'list'), (4, 'of'), (5, 'words.')]

正如另一个答案中所指出的,在提示后放置一个空格是个好主意,这样就可以将它与用户输入的内容分开:

inputwords = input('What keywords are you looking for? ').split()

但是,您的代码不适用于 python2,其中input()函数实际上是通过eval()运行结果字符串:

>>> input()

1 + 2 + 3
6

有关更多信息,请参阅此问题

如果您希望您的代码与 python2 和 python3 兼容,请使用这个小片段:

try:                       
    input = raw_input      
except NameError:          
    pass                   

这将确保input指向函数的 python3 版本。

input(...).split()一个列表。 因此,您只需要:

inputwords = input('What keywords are you looking for?').split()
print(list(enumerate(inputwords)))

请注意,虽然这在 Python 3 中有效,但在 Python 2 中,您必须使用raw_input()函数 - input需要 Python 表达式,并返回计算该表达式的结果。

>>> inputwords = input('What keywords are you looking for?').split()
What keywords are you looking for?This, that and the other
>>> print(list(enumerate(inputwords)))
[(0, 'This,'), (1, 'that'), (2, 'and'), (3, 'the'), (4, 'other')]

在提示字符串的末尾放置一个空格会很有帮助,以清楚地分隔提示和输入。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM