【问题标题】:Python: Splitting an input of unknown length and creating an arrayPython:拆分未知长度的输入并创建一个数组
【发布时间】:2018-08-22 20:59:44
【问题描述】:

在 Python 中,我将如何创建一个包含这种格式的拆分输入的数组:

例如)

(1,2,3)&(6,8,10)&(2,5)&(29,8,6)

-输入可以是任意数量的这些元组。

-我会在 '&' 处拆分并去掉括号

-那我想把它变成一个数组 在这种情况下:

array=
 [[1,2,3],
 [6,8,10],
 [2,5],
 [29,8,6]]

【问题讨论】:

  • something 是字符串吗?

标签: python arrays split strip


【解决方案1】:

如果Something是一个字符串,你可以这样做。

something = "(1,2,3)&(6,8,10)&(2,5)&(29,8,6)"

words = something.split('&')

for i,x in enumerate(words):
    words[i] = x.replace('(','').replace(')','')

或使用列表推导代替 for 循环,

words[:] = [x.replace('(','').replace(')','') for x in words]

【讨论】:

    【解决方案2】:

    如果你有这样的刚性结构,解决方案可能如下

    s = "(1,2,3)&(6,8,10)&(2,5)&(29,8,6)"
    l = [list(map(int, t[1:-1].split(','))) for t in s.split('&')]
    print(l)  # [[1, 2, 3], [6, 8, 10], [2, 5], [29, 8, 6]]
    

    首先你用“&”分割字符串,然后你分割子字符串,从第二个开始到最后一个位置之前的一个,用“,”和map它们作为int或任何其他数字类型

    【讨论】:

      【解决方案3】:

      如果您需要更改输入字符串,这是另一种方法

      data = '(1,2,3)&(6,8,10)&(2,5)&(29,8,6)'
      a = []
      for i in data.split('&'):
          a.append([int(j) for j in i[i.find('(')+1:i.find(')')].split(',')])
      print(a)  #[[1, 2, 3], [6, 8, 10], [2, 5], [29, 8, 6]]
      

      【讨论】:

        【解决方案4】:

        你可以试试这个方法:

        >>> def to_list(s):
        ...     return [int(i) for i in s.strip('()').split(',')]
        ... 
        >>> data = '(1,2,3)&(6,8,10)&(2,5)&(29,8,6)'
        >>> [to_list(item) for item in data.split('&')]
        [[1, 2, 3], [6, 8, 10], [2, 5], [29, 8, 6]]
        

        【讨论】:

          猜你喜欢
          • 2013-11-23
          • 1970-01-01
          • 1970-01-01
          • 2017-03-14
          • 2019-11-29
          • 2016-04-02
          • 1970-01-01
          • 2016-03-11
          • 1970-01-01
          相关资源
          最近更新 更多