Home > front end >  List comprehension in python with multiple if statements
List comprehension in python with multiple if statements

Time:07-09

I am trying to build list similar to this

Position = [1, 1, 1, 1, 1, 1, 1, 
      2, 2, 2, 2, 2, 2, 2, 
     3, 3, 3, 3, 3, 3, 3,
     4, 4, 4, 4, 4, 4, 4,
     5, 5, 5, 5, 5, 5, 5,
     6, 6, 6, 6, 6, 6, 6,
     7, 7, 7, 7, 7, 7, 7,
     8, 8, 8, 8, 8, 8, 8,
     9, 9, 9, 9, 9, 9, 9,
     10, 10, 10, 10, 10, 10, 10,
     11, 11, 11, 11, 11, 11, 11,
     12, 12, 12, 12, 12, 12, 12,
     13, 13, 13, 13, 13, 13, 13,
     14, 14, 14, 14, 14, 14, 14,
     15, 15, 15, 15, 15, 15, 15]

With the list comprehension like below (with one if statement), only the first 7 elements can be created. How can I add multiple if statements?

d = 1 
position = [d if i<7 else d 1 for i in range (105)]

CodePudding user response:

No need for even a single if; just use integer division

[1 i//7 for i in range (7*15)]

CodePudding user response:

Use numpy for creating a list of some value with some repetition, append them together

import numpy as np

numbers_i_want = np.arange(1, 16, 1, dtype=int) #last number not included

arr = np.array([])
for n in numbers_i_want:
    temp = np.full(
        shape=10, # how many ints
        fill_value=n #what int
    )   
    arr= np.concatenate((arr,temp))
print(arr)

CodePudding user response:

The simplest solution in the standard library is to chain multiple iterables together.

from itertools import chain, repeat

Position = list(chain.from_iterable(repeat(i, 7) for i in range(1, 16)))

or use two generators

Position = list(x for i in range(1, 16) for x in repeat(i, 7))

Or, since int values are immutable, list multiplication is a viable solution.

Position = list(chain.from_iterable([i]*7 for i in range(1, 16)))
Position = list(x for i in range(1, 16) for x in [i]*7)
  • Related