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

前提是你 提交于 2020-03-16 06:50:14

问题


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 in my pathlist I have something like this:

pathlist=[C1_01.csv,C1_02.csv,...,Cn_01.csv,Cn_02.csv] 

I would like to have finally a pathlistf ordered or sort with this situation:

pathlistf=[[C1_01.csv,C1_02.csv,...],[C2_01.csv,C2_02.csv,...],...,[Cn_01.csv,Cn_02.csv,...]]

I don't have idea to reorder the path to this way.

Hello again, i got this problem: I would like to ask something very similar to the past case, let suppose i have the next path: path=[case1_Qxxx_cap1_whatever.csv,case1_Qxxx_cap1_whatever2.csv,case1_Qxxx_cap1_whatever3.csv,....,case1_Qxxx_cap2_whatever.csv,case1_Qxxx_cap2_whatever2.csv,case1_Qxxx_cap2_whatever3.csv,case2_Qxxx_cap1_whatever.csv,case2_Qxxx_cap1_whatever2.csv,...,case2_Qxxx_cap2_whatever.csv,case2_Qxxx_cap2_whatever2.csv]

I would like to have this:

pathf=[[[case1_Qxxx_cap1_whatever.csv,case1_Qxxx_cap1_whatever2.csv,...],[case1_Qxxx_cap2_whatever.csv,Qxxx_cap2_whatever2.csv,...]],[[case2_Qxxx_cap1_whatever.csv,case2_Qxxx_cap1_whatever2.csv,...],[case2_Qxxx_cap2_whatever.csv,case2_Qxxx_cap2_whatever2.csv,...]]]


回答1:


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']]



回答2:


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.



来源:https://stackoverflow.com/questions/60128506/how-to-save-a-list-of-string-in-sublists-according-specific-expression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!