如何将扁平列表转换为按固定间隔设置键的字典?
Looking at your example list, the pattern is clear: each standalone string acts as a key, followed by exactly 3 sublists as its values, repeating this structure throughout the list. Here's a straightforward way to convert this into the dictionary you need:
Solution for Fixed 3 Sublists per Key
list_x = ['a', ['j', '1', 'x'], ['k', '2', 'y'], ['a', '3', 'hj'], 'd', ['b', '4', 'df'], ['c', '5', 'er'], ['d', '6', 'ty'], 'g', ['e', '7', 'hj'], ['f', '8', 'bv'], ['g', '9', 'sad'], 'j', ['h', '10', 'kj'], ['i', '11', 'nbv'], ['c', '12', 'uy'], 'n', ['d', '13', 'ipoas'], ['e', '14', 'fg'], ['f', '15', 'as'], 'r', ['g', '16', 'dsad'], ['h', '17', 'fdgdfg'], ['i', '18', 'retrt'], 'u', ['j', '19', 'qwe'], ['k', '20', 'ytgf'], ['n', '21', 'xyz']] result_dict = {} sublists_per_key = 3 # Adjust this number if your interval changes # Iterate through the list in chunks of (1 key + N sublists) for i in range(0, len(list_x), sublists_per_key + 1): if i >= len(list_x): break key = list_x[i] # Grab the next N sublists as values for this key values = list_x[i+1 : i+1+sublists_per_key] # Handle cases where the list ends before a full set of sublists values = values[:sublists_per_key] result_dict[key] = values print(result_dict)
How This Works:
- We use
range()with a step size ofsublists_per_key + 1to jump from one key to the next. - For each key at index
i, we take the nextsublists_per_keyelements as its corresponding values. - The final slice
values[:sublists_per_key]ensures we don't get index errors if the list ends mid-group.
Adjusting for Different Fixed Intervals
If your pattern uses a different number of sublists per key (e.g., 2 instead of 3), just change the sublists_per_key variable to match. For example, 2 sublists per key would use a step size of 3.
Alternative: Flexible Key Detection (If Intervals Vary)
If the number of sublists per key isn't strictly fixed, but keys are always standalone strings and values are always sublists, use this approach to collect values until the next key is found:
result_dict = {} current_key = None current_values = [] for item in list_x: if isinstance(item, str): # Save the previous key-value pair if it exists if current_key is not None: result_dict[current_key] = current_values # Start a new key group current_key = item current_values = [] else: # Add sublist to the current key's values current_values.append(item) # Don't forget the last key-value pair if current_key is not None: result_dict[current_key] = current_values print(result_dict)
This version automatically detects when a new key starts and collects all subsequent sublists until the next key appears.
内容的提问来源于stack exchange,提问作者patronlargibi

