Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add n elements in a list, where n is each item in another list?

I have the following three lists:

numlist = [0,4,0,4,0,4,0,0,4,0,4]
upperlist = ['EF','FA','FE','FY','IF','OF']
lenwords = [2,2,2,2,2,2]

Where each item in lenwords represents the number of characters for each word in upperlist.

I want to add consecutive numbers in numlist n times, where n is equal to n in lenwords, so that the resulting list would look like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

sumlist = [4,4,4,4,4,4]

The objective is to the zip upperlist and sumlist into a list of tuples, which would look something like this:

ziplist = [(4,'EF'), (4,'FA'), (4,'FE'), (4,'FY'), (4,'IF'), (4,'OF')]

I know how to zip both lists, I’m just getting stuck in how to access n in lenwords to add i + i+1 in numlist.

>Solution :

Use a variable to keep track of your progress

numlist = [0, 4, 0, 4, 0, 4, 0, 4, 0, 4, 0, 4]
upperlist = ['EF', 'FA', 'FE', 'FY', 'IF', 'OF']
lenwords = [2, 2, 2, 2, 2, 2]

values = []
count = 0
for n in lenwords:
    values.append(sum(numlist[count:count + n]))
    count += n
print(values)
# [4, 4, 4, 4, 4, 4]

result = list(zip(values, upperlist))
print(result)
# [(4, 'EF'), (4, 'FA'), (4, 'FE'), (4, 'FY'), (4, 'IF'), (4, 'OF')]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading