2041_22T2.Q3

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#!/usr/bin/env python3
import sys

def main():
# 使用集合 (set) 自动处理去重需求
male_surnames = set()

# sys.stdin 允许直接遍历标准输入流,每次迭代读取一行
for line in sys.stdin:
# 去除行末尾的换行符和潜在的空白字符
line = line.strip()
if not line:
continue

# 等效于 cut -d'|'
fields = line.split('|')

# 确保数据格式正确且最后一个字段为 'M' (等效于 grep '|M$')
if len(fields) == 5 and fields[4] == 'M':
# 提取姓名列 (0-based index, 第3列索引为2)
name_field = fields[2]

# 等效于 cut -d',' -f1
surname = name_field.split(',')[0].strip()

# 存入集合自动去重
male_surnames.add(surname)

# sorted() 将无序集合转换为按字母表排序的列表
for surname in sorted(male_surnames):
print(surname)

if __name__ == '__main__':
main()