zoukankan      html  css  js  c++  java
  • python获取多输入

    我们都知道python的input()函数是以字符串的形式输入的,这就产生了一个问题:当我们在一行内输入多个数值时,input()不会去判断输入元素个数,它只管把这行输入以字符串的形式输入,因此我们要得到每一个元素时就需要对字符串分割,再强转成我们需要的类型。这样做明显很麻烦。下面我介绍一种简单的方法:

    >>> a = map(int, input('').split())
    1 2 3
    >>> a
    <map object at 0x000001A955B69AC8>

    如上面代码所示我们成功获得了多个输入,但是此时还是有问题:它的类型是map对象,我们还是无法直接使用。我们只需稍作处理即可:

    >>> b = list(map(int, input('').split()))
    1 2 3
    >>> b
    [1, 2, 3]

    我们看到现在多个输入值已经可以方便使用了。接下我们只需修改map中的数据类型就能得到不同类型的列表:

    >>> c = list(map(float, input('').split()))
    1 2 3
    >>> c
    [1.0, 2.0, 3.0]
    >>> d = list(map(str, input('').split()))
    1 2 3
    >>> d
    ['1', '2', '3']

     下面这种方法比较实用,个人比较推荐:

    >>> e = [int(i) for i in input('').split()]
    1 2 3
    >>> e
    [1, 2, 3]

     当我们知道输入的参数个数时,可以采用如下方法:

    >>> l, r, k = map(int, input().split())
    1 2 3
    >>> l
    1
    >>> r
    2
    >>> k
    3
  • 相关阅读:
    [Quote] Android Graphics Architecture
    New NFC log
    [Quote] 3.6 Namespaces
    NFC DAL(Driver Abstraction Layer) and OSAL(Operating System Abstraction Layer)
    Finance&Invest&Economics URL Links
    Concepts
    Tracking NFC Flow
    NFC log
    [IoE] About AllJoyn™
    [Quote] How does getSystemService() work exactly?
  • 原文地址:https://www.cnblogs.com/marvin-wen/p/11884504.html
Copyright © 2011-2022 走看看