How to save a list of string in sublists according specific expression?

前端 未结 2 1583
[愿得一人]
[愿得一人] 2021-01-22 21:15

I\'m doing a script to save a read path in sublist. Let\'s suppose I have 400 file paths saved in a list, every path has the specific syntax Ci_whaterver.csv, then

2条回答
  •  一个人的身影
    2021-01-22 22:04

    If pathlist is pre-sorted, you can use the following code based on the itertools.groupby.

    from itertools import groupby
    pathlist=['Cn_01.csv', 'C1_02.csv', 'C9_01.csv', 'C9_02.csv', 'Ca_01.csv', 'C9_03.csv', 'Ca_02.csv', 'C1_01.csv', 'Cn_02.csv']
    pathlist.sort()
    groupedfilenames = (list(g) for _, g in groupby(pathlist, key=lambda a: a[:2]))
    print(list(groupedfilenames))
    

    Output:

    [['C1_01.csv', 'C1_02.csv'], ['C9_01.csv', 'C9_02.csv', 'C9_03.csv'], ['Ca_01.csv', 'Ca_02.csv'], ['Cn_01.csv', 'Cn_02.csv']]
    

提交回复
热议问题