Home > OS >  Group List by another list
Group List by another list

Time:11-10

Let’s say I had two lists like this:

l1 = [‘a’,’b’,’c’,’d’,’e’,’f’,’g’,’h’]
l2 = [True, True, True, False, False, True, False, True]

With Python, how could I iterate through these elements in order and group them in groups of 3 or 4 based on l2. So that the output would look like this:

groups = [[‘a’,’b’,’c’],[‘d’,’e’],[‘f’,’g’,’h’]]

Basically the rules are as follows:

  1. Each ”True” is worth 1 point and each “False” is worth 2 points.
  2. No group can have more than 4 points.
  3. Iterate through the lists in order and group them accordingly.

Here's what I've tried:

l1 = ["a","b","c","d","e","f","g","h"]
l2 = [True, True, True, False, False, True, False, True]
groups = []
count = 1
index = 0
while index <= len(l1):
    group = []
    for e,b in zip(l1,l2):
        if len(group) <= 3:
            if b is True:
                group.append(e)
                index  = 1
            else:
                group.append(e)
                group.append("False")
                index  = 1
        else:
            groups.append(group)
            group = []
            index -= 1

CodePudding user response:

From what I understood from your question (it took some effort) this is what you're looking for. I wrote a function that would work.

def group_lists(l1, l2):
    temp_val = 0
    temp_list = []
    groups = []
    for ind in range(len(l1)):
        if l2[ind]:
            temp_val  = 1
        else:
            temp_val  = 2
        print(temp_val, l1[ind])
        if temp_val <= 4:
            temp_list.append(l1[ind])
        else:
            groups.append(temp_list)
            temp_list = []
            temp_list.append(l1[ind])
            if l2[ind]:
                temp_val = 1
            else:
                temp_val = 2
    groups.append(temp_list)
    return groups

Hope this helps!

CodePudding user response:

We can use zip . Here zip(l1,l2) gives us ('a',True),('b',True) ... for each iteration. Then we can simply check conditions when the temp_counter is less than max_limit(4) .If temp_counter is smaller, then add value to temp_list, else add temp_list to "results" List.

l1 = ['a','b','c','d','e','f','g','h']
l2 = [True, True, True, False, False, True, False, True]

max_limit=4
result=[]

temp_list=[]
temp_counter=0

for i,j in zip(l1,l2):
    
    if (max_limit - temp_counter)>=1 and j==True:
        temp_counter =1
        temp_list.append(i)
    
    elif (max_limit - temp_counter)>=2 and j==False:
        temp_counter =2
        temp_list.append(i)
        
    else:
        temp_counter=0
        if j == True:
            temp_counter  =1
        else:
            temp_counter  =2
        result.append(temp_list)
        temp_list=[i]
        
result.append(temp_list)
print(result)
    
  • Related