【问题标题】:Python3 splitting a list using a word+characterPython3使用单词+字符拆分列表
【发布时间】:2020-06-22 10:32:46
【问题描述】:

我有一个列表,如果它与一个单词和一个半列匹配,我想将它的项目拆分为自己的部分。当您查看以下代码和期望的结果时,这将更有意义。

list = [
    'Size: 20inches. Weight: about 1.2kg',
    'Length: pretty long. Body: is plastic.',
    'For all ages. Comes with box'
    ]

期望的结果:

list = [
    'Size: 20inches.',
    'Weight: about 1.2kg',
    'Length: pretty long.', 
    'Body: is plastic.',
    'For all ages. Comes with box'
    ]

【问题讨论】:

    标签: python-3.x list split


    【解决方案1】:
    input_data = [
        'Size: 20inches. Weight: about 1.2kg',
        'Length: pretty long. Body: is plastic.',
        'For all ages. Comes with box',
    ]
    
    output_data = []
    
    for line in input_data:
        s = re.split('(\w+ *:)', line)  # Split line by '<word>:'
        i = 0
        while i < len(s):
            # This is an empty string. Ignore
            if not s[i]:
                i += 1
                continue
            # We found a 'Key:'. Get the 'Value' and add it to output
            elif s[i].endswith(':') and i+1 < len(s):
                new_item = s[i] + s[i+1]
                i += 2
            # We found a lone string. Add it to output
            else:
                new_item = s[i]
                i += 1
            output_data.append(new_item.strip())
    
    print(output_data)
    

    输出:

    ['Size: 20inches.',
     'Weight: about 1.2kg',
     'Length: pretty long.',
     'Body: is plastic.',
     'For all ages. Comes with box']
    

    【讨论】:

      【解决方案2】:

      使用split()

      x_lst = [
          'Size: 20inches. Weight: about 1.2kg',
          'Length: pretty long. Body: is plastic.'
          ]
      
      print([x.split('. ') for x in x_lst])
      

      输出:

      [['Size: 20inches', 'Weight: about 1.2kg'], ['Length: pretty long', 'Body: is plastic.']]                                                                                    
      

      编辑

      如果你想要一个扁平化的列表:

       res = [x.split('. ') for x in x_lst]
       print([item for items in res for item in items])
      

      输出:

      ['Size: 20inches', 'Weight: about 1.2kg', 'Length: pretty long', 'Body: is plastic.']
      

      编辑 2

      我看到您使用新的输入更改了所需的输出:

      res = [x.split('. ') if x != x_lst[-1] else [x] for x in x_lst]     
      print([item for items in res for item in items])
      

      输出:

      ['Size: 20inches', 'Weight: about 1.2kg', 'Length: pretty long', 'Body: is plastic.', 'For all ages. Comes with box'] 
      

      【讨论】:

      • 如果'For all ages. Comes with box' 不是列表中的最后一项,这将不起作用。所以这只是一个适用于特定输入的 hacky 解决方案。此外,您丢失了字符串末尾的点,这可能没什么大不了,但显然不是 OP 想要的。
      • @Asocia 最后的 EDIT 2,涵盖了这种情况。
      • 不,它没有。尝试在输入中再添加一项。您会看到'For all ages. Comes with box' 将被拆分为 2 个项目。
      猜你喜欢
      • 2018-03-13
      • 1970-01-01
      • 2018-06-15
      • 2021-05-26
      • 1970-01-01
      • 1970-01-01
      • 2017-08-16
      • 1970-01-01
      • 2011-09-11
      相关资源
      最近更新 更多