Untitled

mail@pastecode.io avatar
unknown
plain_text
12 days ago
1.0 kB
5
Indexable
Never
def group_files_by_name_start(files):
    grouped_files = {}
    for file in files:
        parts = file.split('_')
        for i in range(1, len(parts)):
            name_start = '_'.join(parts[:i])
            if name_start not in grouped_files:
                grouped_files[name_start] = []
            grouped_files[name_start].append(file)
            # Keep only the most recent group with more than one match
            if len(grouped_files[name_start]) > 1:
                latest_group = name_start

    # Filter the final groups to keep only the latest one with more than one match
    final_group = {latest_group: grouped_files[latest_group]} if 'latest_group' in locals() else {}
    return final_group

# Example usage:
files = [
    'apple_pie.txt', 'apple_crisp.txt', 'banana_bread.txt',
    'banana_muffin.txt', 'cherry_tart.txt', 'cherry_pie.txt'
]

grouped = group_files_by_name_start(files)

# Printing the final group with more than one match
for key, group in grouped.items():
    print(f"Group '{key}': {group}")
Leave a Comment