Creating a new list with a subset of a list using index in python

List:

a = ['a', 'b', 'c', 3, 4, 'd', 6, 7, 8] 

I need a list using a subset using a[0:2],a[4], a[6:] ,

that is, I want a list ['a', 'b', 4, 6, 7, 8]

+6
source share
3 answers

Try new_list = a[0:2] + [a[4]] + a[6:] .

Or, in general, something like this:

 from itertools import chain new_list = list(chain(a[0:2], [a[4]], a[6:])) 

This also works with other sequences and is likely to be faster.

Or you can do it:

 def chain_elements_or_slices(*elements_or_slices): new_list = [] for i in elements_or_slices: if isinstance(i, list): new_list.extend(i) else: new_list.append(i) return new_list new_list = chain_elements_or_slices(a[0:2], a[4], a[6:]) 

But be careful, this will lead to problems if some of the items in your list are themselves lists. To solve this problem, either use one of the previous solutions, or replace a[4] with a[4:5] (or more generally a[n] with a[n:n+1] ).

+13
source

Let's pretend that

 a = ['a', 'b', 'c', 3, 4, 'd', 6, 7, 8] 

and the list of indexes is stored in

 b= [0, 1, 2, 4, 6, 7, 8] 

then a simple single line solution would be

 c = [a[i] for i in b] 
+12
source

The following definition may be more effective than the proposed first proposed solution.

 def new_list_from_intervals(original_list, *intervals): n = sum(j - i for i, j in intervals) new_list = [None] * n index = 0 for i, j in intervals : for k in range(i, j) : new_list[index] = original_list[k] index += 1 return new_list 

then you can use it as below

 new_list = new_list_from_intervals(original_list, (0,2), (4,5), (6, len(original_list))) 
+1
source

Source: https://habr.com/ru/post/955506/


All Articles