Roman Lents
Roman Lents

Reputation: 131

Create lists based on condition in another lists

I have lists below:

    I = [1, 2, 3]
    U = [4, 5, 6]
    N = [7, 8, 9]

I want to get the following:

    for each number in list N I want to get the group of lists like that:
    for N[0] = 7  > P = [I[0], U[0], 0] = [1, 4, 0, 0, 0, 0]
    for N[1] = 8 > P = [I[0], I[1], U[0], U[1], 0, 0] = [1, 2, 4, 5, 0, 0]
    for N[2] = 9 > P = [I[0], I[1], I[2], U[0], U[1], U[2]] = [1, 2, 3, 4, 5, 6]

The idea is that for the first element in list N I want to get the list P that will have the first element from lists I and U and the rest will be zero (the length should be always be the same and equals to len(I) + len(U). In my example, for demonstration purposes, the length on list N equals to 3 but in reality it can be 1000 and more. So I need an algorithm that will iterate through list N and create new lists based on values and positions in lists I and U. It may sound awkward and please ask if you need clarifications.

Upvotes: 0

Views: 508

Answers (1)

Ginger
Ginger

Reputation: 293

The final code is as follows:

i = [1, 2, 3]
u = [4, 5, 6]
n = [7, 8, 9]
l = [i, u] # This works with any number of lists :)
p = []
#Get the total length of all the lists in l
total = 0
for item in l:
  total += len(item)

for y in range(0, len(n) + 1):
  _p = []
  for item in l:
   for x in range(0, y):
    _p.append(item[x])
  for item in range(0, total - len(_p)):
    _p.append(0)
  p.append(_p)
p.pop(0) #Removes mystery empty element

print(p)

Upvotes: 1

Related Questions