一行n个整数,合并排序
时间: 2025-04-23 10:57:33 浏览: 25
### 合并并排序多行包含 n 个整数的数组或列表
对于处理多个包含不同整数的数组或列表,可以采用如下方法来实现合并和排序操作。此过程涉及读取数据、计算每位数字之和以及按照特定条件进行排序。
#### 数据结构设计
为了方便管理和后续的操作,建议使用 Python 中的 `list` 和 `tuple` 来存储原始数值及其对应的位数总和。每一个元组内含两个元素:第一个是原数值;第二个是个位上的所有数字相加的结果。
#### 计算每一位数字之和函数定义
编写一个辅助函数用于求解单个正整数各个位置上数字累加之和:
```python
def sum_of_digits(num):
"""Calculate the sum of digits for a given integer."""
return sum(int(digit) for digit in str(abs(num)))
```
#### 主逻辑流程说明
通过循环迭代每一行输入的数据,将其转化为上述提到的形式,并最终利用内置的 `sorted()` 函数完成基于自定义键值(即位数总和)降序排列的任务。当遇到相同位数总和的情况时,再依据实际数值大小做进一步区分。
以下是完整的解决方案代码片段:
```python
from typing import List, Tuple
def process_and_sort_numbers(data: List[List[int]]) -> List[Tuple[int, int]]:
"""
Process multiple lines of integers by calculating their digit sums,
and sort them based on these sums.
Args:
data (List[List[int]]): A list where each element is a line of integers.
Returns:
List[Tuple[int, int]]: Sorted tuples containing original number and its digit sum.
"""
def sum_of_digits(num: int) -> int:
"""Helper function to calculate the sum of digits for an integer."""
return sum(int(digit) for digit in str(abs(num)))
combined_data = []
for sublist in data:
for item in sublist:
combined_data.append((item, sum_of_digits(item))) # Store as tuple
sorted_result = sorted(combined_data, key=lambda x: (-x[1], x[0]))
return sorted_result
if __name__ == "__main__":
input_lines = [
[348, 792],
[-564, 123],
[987, 654]
]
result = process_and_sort_numbers(input_lines)
for value, total_sum in result:
print(f"{value}: {total_sum}")
```
该程序首先定义了一个帮助者函数 `sum_of_digits` 来获取任意给定整数各位置上的数字之和[^1]。接着,在主功能部分,遍历传入的所有子列表并将其中的每个成员与其相应的位数总和打包成一对儿加入到一个新的集合当中去。最后一步则是调用 Python 自带的 `sorted()` 方法来进行综合考量下的全面排序工作——优先考虑的是位数总和由高至低;而在同一位数总和的情况下,则会依照自然顺序从小到大地安排次序。
阅读全文
相关推荐

















