可以使用Python中的collections模块和sorted函数来实现按照关键字排序行并分组结果的功能。 代码示例:
from collections import defaultdict
def sort_lines_by_keyword(lines, keyword): groups = defaultdict(list) for line in lines: key = line.strip().split()[keyword] groups[key].append(line) return groups
def sort_and_group(lines, keyword): groups = sort_lines_by_keyword(lines, keyword) sorted_groups = sorted(groups.items()) sorted_lines = [] for key, lines in sorted_groups: for line in lines: sorted_lines.append(line) return sorted_lines
lines = ["apple b 1", "banana a 2", "orange c 3", "grape b 4"] sorted_lines = sort_and_group(lines, 1) for line in sorted_lines: print(line)
在此示例中,sort_and_group函数接收两个参数:lines和keyword。lines列表包含需要排序和分组的行。keyword参数是一个整数,指定排序关键字的位置。函数返回按关键字排序后分组的所有行。默认情况下,返回的元素是按字母顺序排列的。