Rafael Castelo Branco
Rafael Castelo Branco

Reputation: 191

Using one list index as reference in a for loop

I am looking to add text from one list (ListC) to another list (ListB) based on boolean values of a third list (ListA). So all elements of ListB gets an addition but it changes based on the index of ListA. The change should occur only when the index in ListA is True.

ListA = [True, False, True, False, False, False, True]

ListB = ['T1', 'T2', 'T3', 'T4', 'T5', 'T6', 'T7']

ListC = ['s1', 's2', 's3']

The expected end result would be a listD (see that first and second elements of List D has s1 and s2 only enters on the third element as in ListA is True, False, True):

ListD = ['s1 + T1', 's1 + T2', 's2 + T3', 's2 + T4', 's2 + T5', 's2 + T6', 's3 + T7']

the idea is to replace the existing code of:

for i in range(0,2):
    ListD[i] = 's1' +  ListB[i]

for l in range (2,5):
    ListD[l] = 's2' + ListB[l]

for w in range(5,7):
    ListD[w] = 's3'+ ListB[w]

Any suggestions on how to do this?

Thanks for the help!

Upvotes: 1

Views: 394

Answers (3)

dmonton
dmonton

Reputation: 1

#!/usr/bin/env python3

ListA = [True, False, True, False, False, False, True]
ListB = ['T1', 'T2', 'T3', 'T4', 'T5', 'T6', 'T7']
ListC = ['s1', 's2', 's3']
ListD = []

count = 0
for i in range(len(ListA)):
    if ListA[i]:
        ListD.append("{} + {}".format(ListC[count], ListB[i]))
    else:
        ListD.append("{} + {}".format(ListC[count], ListB[i]))
        if count < 2:
            count += 1 

Upvotes: 0

Hamza
Hamza

Reputation: 6025

You can use:

cdx = -1
ListD=[]
for bdx, b in enumerate(ListB):
    cdx+=int(ListA[bdx])
    ListD.append(ListC[max(0, cdx)]+' + '+b)
    
ListD

Which outputs:

['s1 + T1', 's1 + T2', 's2 + T3', 's2 + T4', 's2 + T5', 's2 + T6', 's3 + T7']

Although I am not really sure about how you are treating the first True in your list and what would be the output if there is a False at index 0. Assuming you want the first item in the list anyways, this code will work. If you want to do something different with the first False, it might require some changes

Upvotes: 0

busfighter
busfighter

Reputation: 636

In[115]: c = 0
In[116]: for i, flag in enumerate(ListA):
    ...:     ListD.append(ListC[c] + ' + ' + ListB[i])
    ...:     c += int(flag)
    ...:     
In[117]: ListD
Out[117]: ['s1 + T1', 's2 + T2', 's2 + T3', 's3 + T4', 's3 + T5', 's3 + T6', 's3 + T7']

But I don't see that your example takes the first True in mind and that's why my result is different

Upvotes: 1

Related Questions