【问题标题】:Converting List[str] into List[list]将 List[str] 转换为 List[list]
【发布时间】:2023-01-19 15:50:11
【问题描述】:

我需要将第一个列表格式化为与第二个列表相同的格式。

print(incorrent_format_list)
['AsKh', '2sAc', '7hQs', ...]


print(correct_format_list)
[['As', 'Kh'], ['2s', 'Ac'], ['7h', 'Qs'], ...]

我试过了:

for h in incorrect_format_list:
         split_lines = h.split(", ")
# but the print output is this:

['AsKh']  
['2sKh']
['7hQs']


#rather than what i need: 

[['As', 'Kh'], ['2s', 'Ac'], ['7h', 'Qs'], ...]

【问题讨论】:

    标签: python arraylist


    【解决方案1】:

    如果在整个列表中都是这种情况,则按大写字母拆分

    考虑incorrect_list=['AsKh', '2sAc', '7hQs']

    import re
    correct_format_list=[]
    for i in incorrect_list:
        correct_format_list.append(re.split('(?<=.)(?=[A-Z])', i))
    print (correct_format_list)
    

    输出:

    [['As', 'Kh'], ['2s', 'Ac'], ['7h', 'Qs']]
    

    【讨论】:

      【解决方案2】:

      您可以按如下方式对字符串进行切片:

      my_list = ['AsKh', '2sAc', '7hQs']
      
      corrected_list = [[e[:2], e[2:]] for e in my_list]
      
      print(corrected_list)
      

      输出:

      [['As', 'Kh'], ['2s', 'Ac'], ['7h', 'Qs']]
      

      【讨论】:

        【解决方案3】:

        您可以使用 more_itertools 库并对字符串进行切片。然后将这些拆分后的字符串列表附加到输出列表 (fs) 中:

        from more_itertools import sliced
        
        ss = ['AsKh', '2sAc', '7hQs']
        fs = []
        for h in ss:
            split_lines = h.split(", ")
            fs.append(list(sliced(h, 2)))
        
        print(fs)
        

        输出: [['As', 'Kh'], ['2s', 'Ac'], ['7h', 'Qs']]

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-05-20
          • 2020-11-27
          • 2021-09-17
          • 2018-02-20
          • 1970-01-01
          相关资源
          最近更新 更多