如何根据模式将值附加到有序的元组列表?

How to append values to an ordered list of tuples based on a pattern?

我有一点复杂的迭代和连接问题,请允许我提供上下文。我有两个列表:

列表 #1 包含用户列表:

users = ['Alice', 'Bob, 'Gary', 'Trudy', 'Charles', 'Edith', ...]

列表 #2 是表示任意 ID 和家庭成员的元组:

relations = [('0', 'Sister'), ('1', 'Brother'), ('0', 'Grandmother'), ('1', 'Grandfather'), ('2', 'Mother'), ('3', 'Father'), ('4', 'Brother'), ('0', 'Mother'), ('1', 'Father'), ('2', 'Brother'), (...)]

挑战是:

如何将它们合并到一个列表中,其中每个关系 ID 和家庭成员都附加了用户?

例如爱丽丝看起来像: ((Alice, ('0', 'Sister')), (Alice, ('1', 'Brother'))

虽然 Bob 的关系在 '0', 'Grandmother' 之后开始,并在 '4', 'Brother') 结束,而 Gary 的关系则在 '0', Mother 之后。用户列表和关系列表在这方面完全一致。

到目前为止,我想出的是构建某种循环,我在其中检查 relations[i][0] 位置是否为 == '0',但我不确定如何 当 0 再次出现时,停止 追加 Alice,并在该点继续为用户 Bob 迭代,然后是 Gary,等等。

不可预测性是没有最大ID值或预期范围,用户有随机数的关系。

joined_list = []
i = 0
if relations[i][0] == '0'
    joined_list.append((users[i], relations[i]))
    if relations[i][0] == '0'
        break
    do something

似乎更好的结构是 dict,因此每个用户只有一个条目:

combined = {user: [] for user in users}
user = -1

for relation in relations:
    if relation[0] == '0':
        user += 1
    combined[users[user]].append(relation)
>>> combined
{
    'Alice': [('0', 'Sister'), ('1', 'Brother')], 
    'Bob': [('0', 'Grandmother'), ('1', 'Grandfather'), ('2', 'Mother'), ('3', 'Father'), ('4', 'Brother')], 
    'Gary': [('0', 'Mother'), ('1', 'Father'), ('2', 'Brother')], 
    'Trudy': [], 
    'Charles': [], 
    'Edith': []
}