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:
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
.
CodePudding user response:
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')]
CodePudding user response:
You can map over the lenwords
and generate the consecutive sum.
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]
def consecutiveSum(data):
[index, n] = data
return sum(numlist[index:index n])
sumList = map(consecutiveSum, enumerate(lenwords))
print(sumList) # [4, 4, 4, 4, 4, 4]
CodePudding user response:
With numpy:
import numpy as np
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]
x = np.r_[0, lenwords[:-1]].cumsum()
list(zip(np.add.reduceat(numlist, x), upperlist))
It gives:
[(4, 'EF'), (4, 'FA'), (4, 'FE'), (4, 'FY'), (4, 'IF'), (4, 'OF')]