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

前端 未结 2 1601
[愿得一人]
[愿得一人] 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 21:43

    One way will be to create a dictionary and use the part Ci as key and lists of file names starting with Ci will be the value. For example, take pathlist = ['C1_01.csv','C1_02.csv', 'C2_01.csv' , 'C3_01.csv', 'C2_02.csv'], then we will create a dictionary which will store

    {'C1': ['C1_01.csv', 'C1_02.csv'], 'C2': ['C2_01.csv', 'C2_02.csv'], 'C3': ['C3_01.csv']}
    

    Here is the code:

    pathlist = ['C1_01.csv','C1_02.csv', 'C2_01.csv' , 'C3_01.csv', 'C2_02.csv']
    d = {}
    for path in pathlist:
        if path[:2] not in d:
            d[path[:2]] = [path]
        else:
            d[path[:2]].append(path)
    pathlistf = []
    for key in d:
        pathlistf.append(d[key])
    print(pathlistf)
    # Output: [['C1_01.csv', 'C1_02.csv'], ['C3_01.csv'], ['C2_01.csv', 'C2_02.csv']]
    

    Hope this solves the problem. Feel free to ask any doubt.

提交回复
热议问题