非连续身高变量转换:如何用循环高效处理编码错误的身高数据
Hey there! Let's tackle this height encoding conversion problem. First, let's unpack the pattern in your codes—once you see it, the solution becomes way more efficient than manually mapping every single value.
The Core Conversion Logic
Your codes follow a consistent rule:
- A code like
601= 6 feet + 1 inch 400= 4 feet + 0 inches- Since 1 foot = 12 inches, total inches =
(feet * 12) + inches
This means we don't need to hardcode every possible value (like 400 → 48, 401 →49, etc.). Instead, we can parse the code mathematically to extract feet and inches directly.
Using a Loop for Conversion (Python Example)
Let's assume you've already extracted the numeric height codes from your input (stripped out the ID1, ID3 labels, etc.). Here's how to loop through them efficiently:
Step 1: Prepare your input list
# Example list of height codes height_codes = [601, 601, 409, 410, 511, 400]
Step 2: Loop through codes and convert
converted_inches = [] for code in height_codes: # Extract feet (first digit) and inches (last two digits) feet = code // 100 # Integer division to get the hundreds place inches = code % 100 # Modulo to get the remainder (last two digits) # Calculate total inches total = feet * 12 + inches converted_inches.append(total) print(converted_inches) # Output: [73, 73, 57, 58, 71, 48]
Step 3: Add Edge Case Handling (Optional)
If you need to account for invalid codes (e.g., non-integer values, inches over 11), extend the loop with checks:
converted_inches = [] for code in height_codes: # Skip non-integer values if not isinstance(code, int): converted_inches.append(None) continue # Ensure code is 3 digits (pad with leading zero if needed) code_str = str(code).zfill(3) feet = int(code_str[0]) inches = int(code_str[1:]) # Validate inches are within 0-11 if inches > 11: print(f"Warning: Invalid inches ({inches}) in code {code}") converted_inches.append(None) continue total = feet * 12 + inches converted_inches.append(total)
Why This Is Efficient
- O(n) Time Complexity: The loop runs once per code, making it fast even for large datasets.
- Scalable: No need to update the code if new valid height codes are added (like
700for 7ft 0in = 84 inches). - Maintainable: Far easier to debug and adjust than a long chain of
if/elifstatements for every possible code.
R Example (Alternative Language)
If you're working in R, the same logic applies with a loop (or vectorized function, which is also efficient):
height_codes <- c(601, 601, 409, 410, 511, 400) converted_inches <- sapply(height_codes, function(code) { feet <- floor(code / 100) inches <- code %% 100 feet * 12 + inches }) print(converted_inches) # Output: 73 73 57 58 71 48
内容的提问来源于stack exchange,提问作者Marflow

