Home > Back-end >  How to append values to an ordered list of tuples based on a pattern?
How to append values to an ordered list of tuples based on a pattern?

Time:12-10

I have a bit of a complicated iteration and joining problem, please allow me to provide context. I have two lists:

List #1 contains a list of users:

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

List #2 are tuples representing an arbitrary ID and a Family Member:

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

The challenge is:

  • relations for a User start when the ID is 0 in List #2
  • and the end of their relations is marked when 0 is seen again

How can I combine them into one list where each Relation ID and Family Member has the User attached?

For example Alice would look like: ((Alice, ('0', 'Sister')), (Alice, ('1', 'Brother'))

While Bob's relations start right after at '0', 'Grandmother' and end with '4', 'Brother'), and Gary's relations follow-on with '0', Mother. The user list and the relations list in this regard line up precisely.

So far what I've come up with is constructing some kind of loop where I check if the relations[i][0] position is == '0' but I'm not sure how to stop appending Alice when 0 comes up again and have it continue at that point iterating for user Bob, then Gary, and so on.

The unpredictability is that there is no maximum ID value or expected range, users have random numbers of relations.

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

CodePudding user response:

seems like a better structure would be a dict, so you would have just one entry for each user:

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': []
}
  • Related