如何按列表中的路径对文件进行分组

时间:2017-01-10 20:38:24

标签: python list tuples

是否可以通过此字符串列表进行制作:

['/User/someuser/file.py', '/tmp/download/file.zip', '/tmp/download/file2.zip', '/', '/usr/local/bin', '/tmp/file.txt']

制作此列表

[('/tmp/download', ('file.zip', 'file2.zip')), ('/tmp', ('file.txt',)),
 ('/User/someuser', ('file.py',)), ('/', ()), ('/usr/local/bin', ())]

3 个答案:

答案 0 :(得分:3)

您可以将collections.defaultdictos.path.split()一起用作:

from collections import defaultdict
import os

my_list = ['/User/someuser/file.py', '/tmp/download/file.zip', '/tmp/download/file2.zip', '/', '/usr/local/bin', '/tmp/file.txt']
my_dict = defaultdict(list)

for item in my_list:
    if os.path.isdir(item):   # To check path is a directory
        _ = my_dict[item]   # will set default value as empty list
    else:
        path, file = os.path.split(item)
        my_dict[path].append(file)

# where `my_dict` is `dict` object holding value:
# {'/tmp/download': ['file.zip', 'file2.zip'], '/tmp': ['file.txt'], '/usr/local/bin': [], '/': [], '/User/someuser': ['file.py']}

要将my_dict转换为所需格式的列表,请执行以下操作:

>>> my_dict.items()
[   # Formatted in order to make more readable
    ('/tmp/download', ['file.zip', 'file2.zip']), 
    ('/tmp', ['file.txt']), 
    ('/usr/local/bin', []), 
    ('/', []), 
    ('/User/someuser', ['file.py'])
]

答案 1 :(得分:2)

使用os.path.split将路径名拆分为dirname和basename。然后使用@Html.HiddenFor(m => m.Users[i].Id) 将文件分组在一起。

itertools.groupby

打印

import os
from itertools import groupby


l= ['/User/someuser/file.py', '/tmp/download/file.zip', '/tmp/download/file2.zip', '/', '/usr/local/bin', '/tmp/file.txt']

print([(k, tuple(i[1] for i in g)) for k, g in groupby(map(os.path.split, sorted(l)), key=lambda x: x[0])])

答案 2 :(得分:0)

您可以使用groupbyos.path

    import random 
    lotterynumbers = []
    usernumbers = []
    compnum = 0
    usernum = 0
    matches = 0

    #user picks numbers 
    while len(usernumbers) < 6:
        try:
            usernum = int(input("input a number between 1 and 59 "))
        except ValueError: #if the input is not an integer
        print("your input must be a number between 1 and 59 ")
        continue
    if usernum > 59 or usernum < 1:
        print("your number has to be between 1 and 59 ")
        continue
    elif usernum in usernumbers: #if the input has already been entered into the array
        print("you have already used this number")
        continue  
    else:
        usernumbers.append(usernum)

    timesplay = int(input("how many times would you like to play the lottery? "))
    timesplayed = 0

    while timesplayed < timesplay:
        counter = 0
        while len(lotterynumbers) < 6: #means the while loop runs whilst the array has less than 6 values
            compnum = random.randint(1,59) #imports a random number between 1 and 59
            while compnum in lotterynumbers:
                compnum = random.randint(1,59)
            lotterynumbers.append(compnum) #adds numbers to the array

            if usernumbers[counter] in lotterynumbers: 
                matches = matches + 1 #check computer numbers against the user numbers
            counter = counter + 1
        print (lotterynumbers)
        print ("you have ",matches,"matches")
        lotterynumbers = [] #re-sets the array so the computer can find a new list of numbers 
        matches = 0 #re-sets matches to 0 for each draw of the lottery   
        timesplayed = timesplayed + 1  

你明白了,

from itertools import groupby
import os
L = ['/User/someuser/file.py', '/tmp/download/file.zip', '/tmp/download/file2.zip', '/', '/usr/local/bin', '/tmp/file.txt']
#if all files have extention, convert '/usr/local/bin' to '/usr/local/bin/'
L_fix =  [e if os.path.splitext(e)[1] else os.path.join(e,"") for e in L]
[(k,tuple(map(os.path.basename,v))) for k,v in groupby(L_fix, os.path.dirname)]