【问题标题】:How to request a list input from the user in Python?如何在 Python 中向用户请求列表输入?
【发布时间】:2017-07-05 00:40:45
【问题描述】:

我定义了一个需要 3 个参数的函数,其中一个必须是列表。 我发现的一种解决方案仅在列表由整数组成时才有效,这不一定是这种情况(同一列表中的类型可能会有所不同)。 如何向用户请求列表类型输入?例如:当输入类似[1,2,3]的东西时,它被认为是一个列表?

【问题讨论】:

  • 跟题有什么关系?
  • 问题是:如何向用户请求列表类型输入?
  • @JohnDebs:“有什么关系……?”使用 ast,您的问题的答案是微不足道的。试试ast.literal_eval("[1,2,'3']") 它会将列表解析为列表,将整数解析为整数,将字符串解析为字符串。任何其他方法都会做更多的工作(除了使用eval,但这有其自身的安全问题......)

标签: python function slice


【解决方案1】:

如果您完全信任用户输入,则可以使用eval()。假设用户输入字符串[1, 2, 3]

x = input()    # Python 3, use raw_input for Python 2
y = eval(x)    # Dangerous, don't use with untrusted input

print(y)
# [1, 2, 3]

print(len(y))
# 3

更新:

ast.literal_eval 在这里是更好的选择。

import ast

x = input()    # Python 3, use raw_input for Python 2
y = ast.literal_eval(x)

print(y)
# [1, 2, 3]

print(len(y))
# 3

【讨论】:

  • eval 是个危险的想法……只是等着有人输入__import__("shutil").rmtree
  • 同意,这就是为什么我在回答中提到它很危险。如果作者的意图是让脚本在本地以交互方式运行,那么它并不比 shell 提示更危险。
  • 但是为什么在这种情况下建议eval而不是ast.literal_eval
  • ast.literal_eval 显然是更好的选择。你是对的,我想不出使用eval 的理由。我会更新答案以明确这一点。谢谢!
【解决方案2】:

使用ast.literal_eval:

import ast
while True:
    s=raw_input("Enter a list: ")
    s=ast.literal_eval(s)
    if not isinstance(s, list):
        print "Nope! {} is a {}".format(s, type(s)) 
    else:
        break
print s 

如果您想要用户输入元组的选项(例如通过输入1,2,3),请将tuple 添加到isinstance

import ast
while True:
    s=raw_input("Enter a list: ")
    s=ast.literal_eval(s)
    if not isinstance(s, (list, tuple)):
        print "Nope! {} is a {}".format(s, type(s)) 
    else:
        break

【讨论】:

    【解决方案3】:

    保持简单和安全,使用input并自己将输入转换为列表:

    import re
    re.sub("[^\w]", " ", input('-->')).split()
    -->This is a string of words converted into a list
    
    output: 
    
    ['This', 'is', 'a', 'string', 'of', 'words', 'converted', 'into', 'a', 'list']
    

    input 是内置的:https://docs.python.org/3/library/functions.html#input

    【讨论】:

      【解决方案4】:

      这是一种方法:

      $ cat foo.py
      import sys
      input1 = sys.argv[1]
      input2 = sys.argv[2]
      print('Before\n-------')
      print('input1:{},type_of_input1:{}'.format(input1,  type(input1)))
      print('input2:{},type_of_input2:{}'.format(input2,  type(input2)))
      print('After\n-------')
      input1 = input1.split(' ')
      print('input1:{},type_of_input1:{}'.format(input1,  type(input1)))
      print('input2:{},type_of_input2:{}'.format(input2,  type(input2)))
      $
      

      执行输出

      $ python foo.py 'foo bar' bat
      Before
      -------
      input1:foo bar,type_of_input1:<type 'str'>
      input2:bat,type_of_input2:<type 'str'>
      After
      -------
      input1:['foo', 'bar'],type_of_input1:<type 'list'>
      input2:bat,type_of_input2:<type 'str'>
      $
      

      【讨论】:

        猜你喜欢
        • 2022-11-11
        • 2019-06-20
        • 2018-01-11
        • 1970-01-01
        • 1970-01-01
        • 2018-12-25
        • 2017-08-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多