如何将二进制、八进制、四进制列表转为十进制列表并查询最值?
Here's a straightforward, Python-based approach to handle these conversions and calculate the required min/max values. I'll break it down for each of your example lists with runnable code and explanations.
General Approach
The core idea relies on Python's built-in int() function, which can convert a string representation of a number from any base (2 to 36) to decimal. For negative values, we don't need extra handling—int() can parse negative strings directly. Once we have the full decimal list, we use Python's max() and min() functions to get the extreme values.
1. Binary List Conversion
Your binary list: binary_list = [0, 0, 0, 0, 0, 1, 1, 10, 10, 11, 100, 100, 11, 10, 0]
Binary uses base 2. All values here are non-negative, so conversion is straightforward:
binary_list = [0, 0, 0, 0, 0, 1, 1, 10, 10, 11, 100, 100, 11, 10, 0] decimal_binary = [int(str(num), 2) for num in binary_list] print("Decimal binary list:", decimal_binary) print("Max value:", max(decimal_binary)) print("Min value:", min(decimal_binary))
Output:
Decimal binary list: [0, 0, 0, 0, 0, 1, 1, 2, 2, 3, 4, 4, 3, 2, 0]
Max value: 4
Min value: 0
2. Quaternary List Conversion
Your quaternary list: quaternary_list = [-11, -33, -22, -132, -220, -310]
Quaternary uses base 4. We can directly pass negative numbers (converted to strings) to int():
quaternary_list = [-11, -33, -22, -132, -220, -310] decimal_quaternary = [int(str(num), 4) for num in quaternary_list] print("Decimal quaternary list:", decimal_quaternary) print("Max value:", max(decimal_quaternary)) print("Min value:", min(decimal_quaternary))
Output:
Decimal quaternary list: [-5, -15, -10, -30, -40, -52]
Max value: -5
Min value: -52
For example, -310 in base 4 calculates to -(3*4² + 1*4 + 0) = -(48 +4) = -52, which matches the output.
3. Octal List Conversion
Your octal list: octal_list = [62, -220, -36, 5, 0, 1, -12]
Octal uses base 8. Same concise conversion method:
octal_list = [62, -220, -36, 5, 0, 1, -12] decimal_octal = [int(str(num), 8) for num in octal_list] print("Decimal octal list:", decimal_octal) print("Max value:", max(decimal_octal)) print("Min value:", min(decimal_octal))
Output:
Decimal octal list: [50, -144, -30, 5, 0, 1, -10]
Max value: 50
Min value: -144
As a check, -220 in octal is -(2*8² +2*8 +0) = -(128 +16) = -144, which is correct.
Key Notes
- Converting numbers to strings first ensures multi-digit values (like
10in binary) are parsed correctly as base-specific digits, not decimal integers. - The
int()function handles negative signs seamlessly, so we don't need to split the sign from the digits unless you want explicit control for readability. - This approach works for any base between 2 and 36, making it flexible for other number systems too.
内容的提问来源于stack exchange,提问作者user10246367

