Python extract list elements

How to extract elements from a nested list

I have a nested list in the form of [[1,2,3], [3,4,5], [8,6,2,5,6], [7,2,9]] I would like to extract every first item into a new list, every second item into a new list and the rest into a new nested list:

a = [1,3,8,7] b = [2,4,6,2], c = [[3], [5], [2,5,6],[9]] 

Is it possible to avoid using the for loop because the real nested list is quite large? Any help would be appreciated.

4 Answers 4

Ultimately, whatever your solution would be, you’re gonna have to have a for loop inside your code and my advice would be to make it as clean and as readable as possible.

That being said, here’s what I would propose:

arr = [[1,2,3], [3,4,5], [8,6,2,5,6], [7,2,9]] first_arr, second_arr, third_arr = [], [], [] for nested in arr: first_arr.append(nested[0]) second_arr.append(nested[1]) third_arr.append(nested[2:]) 

This is a naive, simple looped solution using list comprehensions, but see if it is fast enough for you.

l = [[1,2,3], [3,4,5], [8,6,2,5,6], [7,2,9]] a = [i[0] for i in l] b = [i[1] for i in l] c = [i[2:] for i in l] 
>>a [1, 3, 8, 7] >>b [2, 4, 6, 2] >>c [[3], [5], [2, 5, 6], [9]] 

At the moment I cannot think a solution without for loops, I hope I will be able to update my answer later.

Читайте также:  Change href src javascript

Here’s a solution using for loops:

data = [[1,2,3], [3,4,5], [8,6,2,5,6], [7,2,9]] list1 = [] list2 = [] list3 = [] for item in data: else_list = [] for index, value in enumerate(item): if index == 0: list1.append(value) elif index == 1: list2.append(value) else: else_list.append(value) list3.append(else_list) print(list1) print(list2) print(list3) 
[1, 3, 8, 7] [2, 4, 6, 2] [[3], [5], [2, 5, 6], [9]] 

Just for fun I share also a performance comparison, great job in using just one for loop Meysam!

import timeit # a = [1,3,8,7] b = [2,4,6,2], c = [[3], [5], [2,5,6],[9]] def solution_1(): data = [[1, 2, 3], [3, 4, 5], [8, 6, 2, 5, 6], [7, 2, 9]] list1 = [] list2 = [] list3 = [] for item in data: else_list = [] for index, value in enumerate(item): if index == 0: list1.append(value) elif index == 1: list2.append(value) else: else_list.append(value) list3.append(else_list) def solution_2(): arr = [[1, 2, 3], [3, 4, 5], [8, 6, 2, 5, 6], [7, 2, 9]] first_arr, second_arr, third_arr = [], [], [] for nested in arr: first_arr.append(nested[0]) second_arr.append(nested[1]) third_arr.append(nested[2:]) def solution_3(): l = [[1, 2, 3], [3, 4, 5], [8, 6, 2, 5, 6], [7, 2, 9]] a = [i[0] for i in l] b = [i[1] for i in l] c = [i[2:] for i in l] if __name__ == "__main__": print("solution_1 performance:") print(timeit.timeit("solution_1()", "from __main__ import solution_1", number=10)) print("solution_2 performance:") print(timeit.timeit("solution_2()", "from __main__ import solution_2", number=10)) print("solution_3 performance:") print(timeit.timeit("solution_3()", "from __main__ import solution_3", number=10)) 
solution_1 performance: 9.580000000000005e-05 solution_2 performance: 1.7200000000001936e-05 solution_3 performance: 1.7499999999996685e-05 

Источник

extract from a list of lists

How can I extract elements in a list of lists and create another one in python. So, I want to get from this:

all_list = [['1 2 3 4','2 3 4 5'],['2 4 4 5', '3 4 5 5' ]] 
for i in xrange(len(all_lists)): newlist=[] for l in all_lists[i]: mylist = l.split() score1 = float(mylist[2]) score2 = mylist[3] temp_list = (score1, score2) newlist.append(temp_list) list_of_lists.append(newlist) 

I want to get 3rd and 4th digits of each element of the list in the «all_list» list. Sorry, don’t know how else to explain this.

3 Answers 3

You could use a nested list comprehension. (This assumes you want the last two «scores» out of each string):

[[tuple(l.split()[-2:]) for l in list] for list in all_list] 

It could work almost as-is if you filled in the value for mylist — right now its undefined.

Hint: use the split function on the strings to break them up into their components, and you can fill mylist with the result.

Hint 2: Make sure that newlist is set back to an empty list at some point.

First remark, you don’t need to generate the indices for the all_list list. You can just iterate over it directly:

for list in all_lists: for item in list: # magic stuff 

Second remark, you can make your string splitting much more succinct by splicing the list:

values = item.split()[-2:] # select last two numbers. 

Reducing it further using map or a list comprehension; you can make all the items a float on the fly:

# make a list from the two end elements of the splitted list. values = [float(n) for n in item.split()[-2:]] 

And tuplify the resulting list with the tuple built-in:

values = tuple([float(n) for n in item.split()[-2:]]) 

In the end you can collapse it all to one big list comprehension as sdolan shows.

Of course you can manually index into the results as well and create a tuple, but usually it’s more verbose, and harder to change.

Took some liberties with your variable names, values would tmp_list in your example.

Источник

5 Easy Ways To Extract Elements From A Python List

How To Extract Elements Png

Let’s learn the different ways to extract elements from a Python list When more than one item is required to be stored in a single variable in Python, we need to use lists. It is one of python’s built-in data functions. It is created by using [ ] brackets while initializing a variable.

In this article, we are going to see the different ways through which lists can be created and also learn the different ways through which elements from a list in python can be extracted.

1. Extract Elements From A Python List Using Index

Here in this first example, we created a list named ‘firstgrid’ with 6 elements in it. The print statement prints the ‘1’ element in the index.

firstgrid=["A","B","C","D","E","F"] print(firstgrid[1])

2. Print Items From a List Using Enumerate

Here, we created a variable named ‘vara’ and we filled the elements into the list. Then we used ‘varx’ variable to specify the enumerate function to search for ‘1,2,5’ index positions.

vara=["10","11","12","13","14","15"] print([varx[1] for varx in enumerate(vara) if varx[0] in [1,2,5]])

3. Using Loops to Extract List Elements

You can also Extract Elements From A Python List using loops. Let’s see 3 methods to pull individual elements from a list using loops.

Method 1:

Directly using a loop to search for specified indexes.

vara=["10","11","12","13","14","15"] print([vara[i] for i in (1,2,5)])

Method 2:

Storing list and index positions into two different variables and then running the loop to search for those index positions.

elements = [10, 11, 12, 13, 14, 15] indices = (1,1,2,1,5) result_list = [elements[i] for i in indices] print(result_list)

Method 3:

In this example, we used a different way to create our list. The range function creates a list containing numbers serially with 6 elements in it from 10 to 15.

numbers = range(10, 16) indices = (1, 1, 2, 1, 5) result = [numbers[i] for i in indices] print(result)

4. Using Numpy To View Items From a List

We can also use the popular NumPy library to help us Extract Elements From A Python List. Let’s see how that can be done here using two different methods.

Method 1:

Here, we used the numpy import function to print the index specified in variable ‘sx’ from the elements present in list ‘ax’ using np.array library function.

ax = [10, 11, 12, 13, 14, 15]; sx = [1, 2, 5] ; import numpy as np print(list(np.array(ax)[sx]))

Method 2:

This example uses variable storing index positions and another variable storing numbers in an array. The print statement prints the index positions stored in variable ‘sx’ with respect to a variable containing the list – ‘ay’.

sx = [1, 2, 5]; ay = np.array([10, 11, 12, 13, 14, 15]) print(ay[sx])

5. Extract Elements Using The index function

vara=["10","11","12","13","14","15"] print([vara[index] for index in (1,2,5,20) if 0 

Conclusion

This article explains in great detail the different methods available to search and extract elements from a python list. We learned in this article, how lists are made, the different types of python functions through which elements are extracted from the list. It is hoped that this article might have helped you.

Источник

Extract list element in Python

That list comprehension isn't really doing anything for you. Why not simply print itertools.combinations(range(k, r), r - k) ?

2 Answers 2

If you want to give [(0, 1)] a value, you can use a dictionary, but you have to use (0, 1) instead of [(0, 1)] because you would otherwise get TypeError: unhashable type: 'list' . If you want a "random value", I guess you can use the random module:

import random <(0, 1) : random.randint(1,10)># This is just an example, of course 

To store all the outputs in one list, you can use a massive list comprehension:

>>> [list(itertools.combinations(range(x, i), i-x)) for x in range(0, items+1) for i in range(0, items+1) if (i-x) > 0] [[(0,)], [(0, 1)], [(0, 1, 2)], [(0, 1, 2, 3)], [(1,)], [(1, 2)], [(1, 2, 3)], [(2,)], [(2, 3)], [(3,)]] 

For (b), I want to store all generated combinations into an array, now, "res" is not an array. I tried res[i] = list(itertools.combinations(range(k, r), r-k)) , where i=0, res = [], but it gives "IndexError: list assignment index out of range".

arh. Sorry, I am coding python with a C mind. I used res.append(list(itertools.combinations(range(k, r), r-k))) . It works thanks.

I initially posted this as a comment, but I think it's really an answer.

You're misapplying itertools.combinations , and it's getting in the way of your ability to get your data in a convenient way. itertools.combination(range(k, r), r-k) is always going to yield exactly one value, range(k,r) . That's unnecessary; you should just use the range directly.

However, the for and if statements you use to produce your k and r values are a combination. Instead of the three levels of statements in your original code, you can use for k, r in itertools.combinations(range(items+1), 2) . I suspect you were trying to do this when you put the itertools.combinations call in your code, but it ended up in the wrong place.

So, to finally get around to your actual question: To access your data, you need to put all your items into a single data structure, rather than printing them. A list comprehension is an easy way to do that, especially once you've simplified the logic producing them, as my suggested changes above do:

import itertools items = 4 results = [range(k, r) for k,r in itertools.combinations(range(items+1),2)] print results # prints [[0], [0, 1], [0, 1, 2], [0, 1, 2, 3], [1], [1, 2], [1, 2, 3], [2], [2, 3], [3]] 

If you need to access the individual items, you use indexing into the results list, then into its member lists, as necessary.

print results[6] # prints [1, 2, 3] print results[6][0] # prints 1 

Источник

Оцените статью