Python:如何比较两个列表,如果存在,则获取有关它们的所有详细信息

Python: How to compare two lists and if it is present, get all the details about them

我有一个 1000 行的 tsv 数据,其中包含数十列,并以我从 Google 电子表格中获得的名称和用户名开始进行相应排列,我需要在其中提取所有数据,其中 1000 个中只有 400 个通过使用他们的用户名并随机将他们分成 40 人一组。

我所做的是: 我从 1000 个 tsv 中精心挑选了 400 个用户名。 现在我需要将这 400 个随机分成 10 个独立的组。 (我使用在线列表洗牌器做到了)

下面是我将 400 人分成 40 人一组的 python 脚本。

person_list = []
max_person_in_a_class = 40

with open("randomized_participants.txt", "r") as group_input:
    iterator = 1
    for line in group_input:
        line = line.strip("\n")
        if iterator == max_person_in_a_class:
            iterator = 1
        else:
            person_list.append(line)
            iterator += 1
i = 1
k = 1
print("\nGroup {}".format(k))
for person in person_list:
    if i != 41:
        print("{} {}".format(i, person))
        i += 1  
    else:
        print("\nGroup {}".format(k+1))
        i = 1
        k += 1

我成功地将这 400 人分成了 10 个不同的组。

现在类似于搜索功能,我需要从 tsv 中获取使用用户名的人的详细信息。

例如: TSV 文件包含姓名、用户名、年龄、Phone 号码、电子邮件、地址、薪水、测验分数。 同时精选文件包含用户名。

通过使用 Handpicked 的用户名与 TSV 的用户名匹配,得到完整的姓名、用户名、Phone 号码、电子邮件等

我想使用来自 Handpicked 的 'John' 和 'Mary',并希望自动执行从 TSV 文件中获取他们的详细信息(例如电子邮件、地址、薪水)的任务。

with open('shortlisted.tsv', 'r') as tsv:
    for person_details in tsv:
        person_details = person_details.strip("\n")
        for person in person_list:
            if person in person_details:
                print(person)
            else:
                print("No match found")

来自 randomized_participants.txtshortlisted.tsv 的一行示例 Line from randomized_participants.txt and shortlisted.tsv

希望有人能指导我解决我遗漏的问题或这个问题的术语。 或者替代方案。

提前致谢!

希望下面的内容足以解决您的问题。

# Using dict to store person data for flexibility

person_data = {}
# Simplified getting people into groups

N_PER_GROUP = 40
groups = []

with open('randomized_participants.txt', 'r') as f:
    group = []
    for (i, line) in enumerate(f.readlines()):
        person = line.strip()
        if i and not i % N_PER_GROUP:
            groups.append(group)
            group = []
        group.append(person)
        person_data[person] = []
    groups.append(group)
# Printing groups for debugging

for (i, group) in enumerate(groups):
    print(f'Group {i + 1:>2}')
    for person in group:
        print(f'\t{person}')
    print()
# Collating each person's details

with open('shortlisted.tsv', 'r') as tsv:
    
    for line in tsv.readlines():
        details = line.split('\t')
        username = details[3]  # 3 b/c it was column D in your screenshot
        if username in person_data:
            person_data[username] = details
# Printing person data for debugging

for (person, data) in person_data.items():
    print(f'{person}: {data}')

请注意,虽然您可以删除 person_data 并仅使用组中的名称,但如果您这样做,查找给定用户名是否在每一行中的查询将变成 O(n•m) 而不是 O(n)(除非你切换到集合而不是列表,但对于这个应用程序,字典的内存使用不是问题)。