给定一个名字列表,如何打印出名字相同的名字?

Given a list with names, how to print out those names, where the first name is same?

我正在尝试编写一个函数,其中给定名称(始终只是名字、姓氏),并且该函数收集具有相同名字的名称。到目前为止我得到了这个,但我不知道如何继续取回全名。

def same_first_name(people):
  for i in range(len(people)):
    b=people[i].split()
    print(b)
  if b[0] == b[0]:
    

例如:

same_first_name(["Anna Smith", "Barbara Wia", "Anna Brien"]) 

returns

["Anna Smith",  "Anna Brien"]

我不是 100% 清楚你想要实现的目标,但这里有一个函数,它接受一个名字列表,并制作一个字典,其中键是名字,值是列表将密钥作为名字的人的姓氏:

def same_first_name(people):
    split_names = [p.split() for p in people]
    first_names_set = set(p[0] for p in split_names)
    first_names_dict = {
        first_name: [p[1] for p in split_names if p[0] == first_name]
        for first_name in first_names_set
    }
    return first_names_dict

people = ["John Smith", "John Rogers", "Jack Jones", "Jack Smith", "Bill Bong"]

print(same_first_name(people))

控制台输出:

{'Jack': ['Jones', 'Smith'], 'Bill': ['Bong'], 'John': ['Smith', 'Rogers']}

鉴于您在评论中的澄清,这里是一个列表,其中添加了每个人,他们与列表中的至少一个其他人有相同的名字:

def same_first_name(people):
    split_names = [p.split() for p in people]
    first_names_list = [p[0] for p in split_names]
    first_names_set = set(first_names_list)
    first_name_counts_dict = {
        first_name: first_names_list.count(first_name)
        for first_name in first_names_set
    }
    duplicated_first_names = [
        p for p in people if first_name_counts_dict[p.split()[0]] >= 2
    ]
    return duplicated_first_names

people = ["John Smith", "John Rogers", "Jack Jones", "Jack Smith", "Bill Bong"]

print(same_first_name(people))

控制台输出:

['John Smith', 'John Rogers', 'Jack Jones', 'Jack Smith']