Loop to select specific numbers from a given list

Viewed 566

My problem is that in python i have a list of 1000 numbers. I want to select first 20 and store in "A" (another list) and next 30 in "B"(another list), again next 20 in "A", next 30 in "B" untill the list ends. How to do that? Can anyone help please?

4 Answers

I made a function that can do what you're asking

def split_list(lst, gap1, gap2):
    tmp = lst.copy()
    out1, out2 = [], []
    while tmp:
        out1.extend(tmp[:gap1])
        tmp = tmp[gap1:]
        
        out2.extend(tmp[:gap2])
        tmp = tmp[gap2:]
    return out1, out2

gap1 and gap2 are the length of each subset you want to store, so in your case gap1=20 and gap2=30.

Example

numbers = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
A, B = split_list(numbers, 2, 3)

print(A)
print(B)

You could use two nested list comprehension for this:

nums = list(range(2000))
A = [x for i in range( 0, len(nums), 50) for x in nums[i:i+20]]
B = [x for i in range(20, len(nums), 50) for x in nums[i:i+30]]

That means (for A): Starting at index 0, 50, 100 etc., take the next 20 elements and add them to A. Analogous for B. You might also use itertools.islice for the nums[i:i+n] part to avoid creating a bunch of temporary sub-lists.

Of course, this assumes that A and B do not already exist. If they do, and you want to add elements to them, use a regular loop and extend (not tested):

for i in range(0, len(nums), 50):
    A.extend(nums[i   :i+20])
    B.extend(nums[i+20:i+50])

You do not have to check the indices again within the loop; if i+20 is already bigger than the last index in the list, B will just get extended with the empty list in the last step.

Let's first define the followings:

A = [] #empty list
B = [] #empty list

And let's call your first list (that includes 1000 numbers), as my_list.

Then, a simple solution can be as following:

counter = 0
c_a = 2
c_b = 3
while (counter < len(my_list)):
    A = A + my_list[counter:counter+c_a]
    B = B + my_list[counter+c_a : counter + c_a + c_b]
    counter = counter + c_a + c_b 

I suggest generating a 2D nested list, which contains sublists each having 20 elements in it. Here is a one line way of doing that with a list comprehension:

x = range(1, 1001)
output = [x[idx*20:(idx*20 + 20)] for idx in range(0, len(x) / 20)]

Here is a version which operates on a smaller set of data, for demonstration purposes:

x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
output = [x[idx*3:(idx*3 + 3)] for idx in range(0, len(x) / 3)]
print(output)  # [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Related