【问题标题】:Python- Turning user input into a listPython-将用户输入转换为列表
【发布时间】:2015-03-31 00:03:15
【问题描述】:

有没有办法要求用户输入并将他们的输入转换为列表、元组或字符串?我想要将一系列数字插入矩阵。我可以告诉他们在控制台中输入所有数字,不带空格并遍历它们,但还有其他方法吗?

【问题讨论】:

    标签: python input


    【解决方案1】:

    您可以简单地执行以下操作:

    user_input = input("Please provide list of numbers separated by comma, e.g. 1,2,3: ")
    
    a_list =  list(map(float,user_input.split(',')))
    print(a_list)
    # example result: [1, 2, 3]
    

    【讨论】:

    • 非常感谢。字面意思是今天才学地图,所以没想用它
    • 应该真的使用 try/except 投射时,有很多方法会引发错误
    • 我还建议用空格分隔元素并使用普通的.split(),因为它会自动处理项目之间的多个空格。即'1 2 3 4 5'.split() --> ['1', '2', '3', '4', '5']
    • 你们都对。我的回答是众多可能性之一。请随时提供其他答案。
    【解决方案2】:

    如果您正在使用 NumPy,它支持 MATLAB 风格的矩阵定义:

    import numpy as np
    s = raw_input('Enter the matrix:')
    matrix = np.matrix(s)
    

    例如

    Enter the matrix:1 2 3; 4 5 3
    

    matrix 设置为:

    matrix([[1, 2, 3],
            [4, 5, 3]])
    

    用空格分隔每行的条目,用分号分隔每行。

    【讨论】:

      【解决方案3】:

      如果您想要一个列表,当它发现数字之间有空格时自动放置逗号,请使用:

      query=input("enter a bunch of numbers: ")
      a_list = list(map(int,query.split())) 
      print(a_list)
      

      *split() 将用逗号分隔它们,无需输入

      *例如。 1 2 3 4 5 = [1, 2, 3, 4, 5]

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-27
        • 1970-01-01
        • 1970-01-01
        • 2017-05-02
        • 1970-01-01
        相关资源
        最近更新 更多