Python如何解析含字母数字的字符串为float并处理单位转换及嵌套结构?
Solution for Parsing and Converting Storage Capacity Strings in Nested Structures
Got it, let's walk through how to solve this problem. You need to process those storage capacity values (like 56.5T or 181G) nested inside a dictionary of lists of tuples—converting terabytes to gigabytes (multiplying by 1024) and parsing all values to floats. Here's a straightforward Python implementation:
Step 1: Create a Helper Function to Parse Single Capacity Strings
First, let's make a function that takes a single capacity string (e.g., '56.5T') and returns its gigabyte equivalent as a float:
def parse_capacity(cap_str): # Split the string into numeric part and unit num_part = [] unit = "" for char in cap_str: if char.isdigit() or char == ".": num_part.append(char) else: unit = char.upper() # Handle lowercase units (like 't') gracefully # Convert numeric part to float try: num_value = float("".join(num_part)) except ValueError: raise ValueError(f"Invalid numeric format in capacity string: {cap_str}") # Convert to gigabytes based on unit if unit == "T": return num_value * 1024 elif unit == "G": return num_value else: # Optional: Adjust this to handle other units or return original value raise ValueError(f"Unsupported storage unit: {unit}")
Step 2: Process the Entire Nested Dictionary
Next, we'll build a function to traverse the entire input structure, applying our helper function to each capacity value while preserving the original structure:
def process_storage_data(input_dict): processed_data = {} for hv_name, tuple_list in input_dict.items(): processed_tuples = [] for item_tuple in tuple_list: # Keep the first element (identifier) as-is, process the next two capacity values identifier = item_tuple[0] parsed_cap1 = parse_capacity(item_tuple[1]) parsed_cap2 = parse_capacity(item_tuple[2]) processed_tuples.append((identifier, parsed_cap1, parsed_cap2)) processed_data[hv_name] = processed_tuples return processed_data
Step 3: Test with Your Example Input
Let's run this with your sample input to verify:
# Your original input input_data = { 'HV01': [('c50', '8G', '118G'), ('c5d0', '26G', '22.3G')], 'HV02': [('c5t6005Dd0', '790G', '162G'), ('c5t60', '203G', '34.8G'), ('c5t6d0', '56.5T', '112G')] } # Process the data result = process_storage_data(input_data) # Print the output for hv, entries in result.items(): print(f"{hv}:") for entry in entries: print(f" {entry[0]}: {entry[1]} GB, {entry[2]} GB")
Expected Output
HV01: c50: 8.0 GB, 118.0 GB c5d0: 26.0 GB, 22.3 GB HV02: c5t6005Dd0: 790.0 GB, 162.0 GB c5t60: 203.0 GB, 34.8 GB c5t6d0: 57856.0 GB, 112.0 GB
Key Notes
- Unit Flexibility: The helper function converts units to uppercase, so it works with lowercase
't'or'g'if your input has those. - Error Handling: We added basic error handling for invalid numeric formats or unsupported units—you can adjust this to return
Noneor skip invalid entries if needed. - Structure Preservation: The output maintains the exact same nested structure as the input, only modifying the capacity values.
内容的提问来源于stack exchange,提问作者Mieszko Czerniak
相关产品推荐
相关产品推荐

