【问题标题】:Python split text and place into arrayPython拆分文本并放入数组
【发布时间】:2013-06-12 10:16:16
【问题描述】:

我真的不知道如何用英语解释它,但是:

inputText = "John Smith 5"

我想拆分它并将其插入到 nameArray 并将 5(string) 变成一个整数。

nameArray = ["John", "Doe", 5]

然后将nameArray放到fullNameArray

fullNameArray = [["John", "Doe", 5], ["John", "Smith", 5]]

【问题讨论】:

    标签: python arrays list split


    【解决方案1】:

    在这里使用异常处理和int()

    >>> def func(x):
    ...     try:
    ...         return int(x)
    ...     except ValueError:
    ...         return x
    ...     
    >>> inputText = "John Smith 5"
    >>> spl = [func(x) for x in inputText.split()]
    >>> spl
    ['John', 'Smith', 5]
    

    如果您确定它始终是必须转换的最后一个元素,那么试试这个:

    >>> inputText = "John Smith 5"
    >>> spl = inputText.split()
    >>> spl[-1] = int(spl[-1])
    >>> spl
    ['John', 'Smith', 5]
    

    使用nameArray.append 将新列表附加到它:

    >>> nameArray = []                              #initialize nameArray as an empty list  
    >>> nameArray.append(["John", "Doe", 5])        #append the first name
    >>> spl = [func(x) for x in inputText.split()]
    >>> nameArray.append(spl)                       #append second entry
    >>> nameArray
    [['John', 'Doe', 5], ['John', 'Smith', 5]]
    

    【讨论】:

    • 我使用了您的第二个代码,但现在我的问题是我无法将列表填充为 (spl =)... 是否可以使用 append 到 spl 以及拆分?
    • @BlupDitzz 您的nameArray 必须是列表列表才能获得所需的输出。
    • 当我只输入一个名字时,我得到了我想要的输出。当我输入第二个名字时,第二个名字是只打印出来的
    • @BlupDitzz 我已经更新了我的代码,尝试做类似的事情。
    【解决方案2】:

    您正在寻找nameArray = inputText.split()

    以下代码适用于字符串中的任何数字

    所以假设输入在一个名为 inputTextList 的列表中:

    fullNameArray = []
    for inputText in inputTextList:
        nameArray = inputText.split()
        nameArray = [int(x) if x.isdigit() else x for x in nameArray]
        fullNameArray.append(nameArray)
    

    【讨论】:

      【解决方案3】:
      >>> fullnameArray = [["John", "Doe", 5]] 
      >>> inputText = "John Smith 5"
      >>> fullnameArray.append([int(i) if i.isdigit() else i for i in inputText.split()])
      >>> fullnameArray
      [['John', 'Doe', 5], ['John', 'Smith', 5]]
      

      list comprehension 中带有conditional expression ("ternary operator") 的第三行(如果您不熟悉该语法)也可以写成:

      nameArray = []
      for i in inputText.split():
          if i.isdigit():
              nameArray.append(int(i))
          else:
              nameArray.append(i)
      fullnameArray.append(sublist)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-01-17
        • 1970-01-01
        • 1970-01-01
        • 2011-07-24
        • 1970-01-01
        • 1970-01-01
        • 2017-06-01
        • 1970-01-01
        相关资源
        最近更新 更多