如何为现有列表的每个元素生成新列表(也已生成)?

How to generate new list for each element of existing list (which is also generated)?

我有包含一些路径的列表:

['folder1/folder2/Module1'、'folder4/folder5/Module2'、'folder7/folder8/Module3'、'folder12/folder13/Module4'、'folder17/folder20/folder50/Module5' ..等]

提取该列表的每个元素并创建新列表或其他地方以使用其特定名称存储该路径的最佳方法是什么?

Mu 当前代码用于遍历列表的每个元素并将其一一存储,但我无法为每个元素生成新列表,不确定是否可能:

for j in range(len(listOfPaths)):
  del pathList[:]
  path = listOfPaths[j]
  pathList.append(path)

所以澄清一下,最后我需要的是获得一个列表 [Module1] 只包含 'folder1/folder2/Module1',第二个列表 [Module2] 只包含到 Module2 的路径,等等......

检查这个?

temp=['folder1/folder2/Module1', 'folder4/folder5/Module2', 'folder7/folder8/Module3', 'folder12/folder13/Module4', 'folder17/folder20/folder50/Module5']
# List initialization
Output = [] 
  
# Using Iteration to convert 
# element into list of list
for elem in temp:
    temp3=[]
    temp3.append(elem)
    Output.append(temp3)
  
# printing
print(Output)

输出:

[['folder1/folder2/Module1'], ['folder4/folder5/Module2'], ['folder7/folder8/Module3'], ['folder12/folder13/Module4'], ['folder17/folder20/folder50/Module5']]

我想你可以试试这个:

输入=["stra", "strb"]

输出=列表(地图(lambda x: [x], 输入))

在这里使用字典可能比使用列表更好。

#!/usr/bin/env python3
import os

paths = []

paths.append("folder1/subfolderA/Module1")
paths.append("folder2/subfolderB/Module1")
paths.append("folder3/subfolderC/Module1")

paths.append("folder4/subfolderD/Module2")
paths.append("folder5/subfolderE/Module2")

paths.append("folder6/subfolderF/Module50")



# create an empty dictionary
modulesDict = {}
# it will look like this:
#  "ModuleX" -> ["path1/to/ModuleX", "path2/to/ModuleX", ...]
#  "ModuleY" -> ["path3/to/ModuleY", "path4/to/ModuleY", ...]

for path in paths: # loop over original list of paths
    # take only the "ModuleX" part
    moduleName = os.path.basename(os.path.normpath(path))
    # check if its already in our dict or not
    if moduleName in modulesDict:
        # add the path to the list of paths for that module
        modulesDict.get(moduleName).append(path)
    else:
        # create an new list, with only one element (only the path)
        modulesDict[moduleName] = [path]


print(modulesDict)


输出:(有点格式化)

{
'Module1':
    ['folder1/subfolderA/Module1', 'folder2/subfolderB/Module1', 'folder3/subfolderC/Module1'],
'Module2':
    ['folder4/subfolderD/Module2', 'folder5/subfolderE/Module2'],
'Module50':
    ['folder6/subfolderF/Module50']
}