Python自定义排序列表:能否无需转字典实现?附转字典方法
Great question! Let's break this down step by step to address both of your questions.
1. Can we sort without converting to a dictionary?
Absolutely! You can work directly with the original string in your Data list to build the ordered result. Here's a straightforward approach:
- First, split the single string into individual key-value pairs.
- Iterate through your
keyorderlist, and for each key, find the matching pair from the split string. - Build your final ordered list by appending these matched pairs in the desired sequence.
Here's the code implementation:
Data = ['ID:123 GE:m FN:Amir LN:Maleki EM:a@b.c MN:0400101010 ST:VIC'] keyorder = ['ID', 'GE','FN','LN','MN','EM', 'ST'] # Split the string into separate key-value pairs kv_pairs = Data[0].split() final_ordered = [] for key in keyorder: # Find the pair that matches the current key for pair in kv_pairs: if pair.startswith(f"{key}:"): k, v = pair.split(':', 1) # Split only once to handle values with colons (if any) # Convert ID to integer like your original dictionary example if key == 'ID': v = int(v) final_ordered.append((k, v)) break print(final_ordered)
This will output exactly the same result as your dictionary-based approach:
[('ID', 123), ('GE', 'm'), ('FN', 'Amir'), ('LN', 'Maleki'), ('MN', '0400101010'), ('EM', 'a@b.c'), ('ST', 'VIC')]
2. How to convert the original list to your target dictionary?
If you do want to convert the Data list to the dictionary you showed, it's simple with a loop or dictionary comprehension. Here are two ways to do it:
Option 1: Using a basic loop
Data = ['ID:123 GE:m FN:Amir LN:Maleki EM:a@b.c MN:0400101010 ST:VIC'] d = {} # Split the string into key-value pairs, then process each pair for pair in Data[0].split(): key, value = pair.split(':', 1) # Convert ID to integer as in your example if key == 'ID': value = int(value) d[key] = value print(d)
Option 2: Using a concise dictionary comprehension
Data = ['ID:123 GE:m FN:Amir LN:Maleki EM:a@b.c MN:0400101010 ST:VIC'] d = { key: int(value) if key == 'ID' else value for pair in Data[0].split() for key, value in [pair.split(':', 1)] } print(d)
Both methods will output your target dictionary:
{'ID': 123, 'GE': 'm', 'FN': 'Amir', 'LN': 'Maleki', 'EM': 'a@b.c', 'MN': '0400101010', 'ST': 'VIC'}
内容的提问来源于stack exchange,提问作者KenjiChan1212
相关产品推荐
相关产品推荐

