How to extract python list

How to Extract an Element from a List in Python

How to Extract an Element from a List in Python | Extract an element in the sense to obtain a particular element from the list, to achieve this python provides several predefined methods and functions. Also See:- How to Find the Length of a List in Python

  1. Python extract number from list
  2. Python extract string from list
  3. Python select list elements by index
  4. Python select elements from list by condition
  5. How to select the last element in a list python
  6. Write a python program to select an item randomly from a list

Python Extract Number from List

Here, we extract a number from the list string, we have used the split() method to extract the numbers. split() is a predefined method in python which cuts the specified character and returns other characters in the list.

list = ['Rs. 3', 'Rs. 8', 'Rs. 80', 'Rs. 25'] print("Given list : " + str(list)) res = [int(sub.split('.')[1]) for sub in list] print("List after extraction: " + str(res))

Given list : [‘Rs. 3’, ‘Rs. 8’, ‘Rs. 80’, ‘Rs. 25’]List after extraction: [3, 8, 80, 25]

Читайте также:  Python как удалить дубликаты

Python Extract String from List

Now, we extract a string from the list, we use for loop we find the match, hence it checks for the particular substring and returns the string.

list = ['Mark', 'Hark', 'Cark', 'Mack'] match = [s for s in list if "ark" in s] print(match)

Источник

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.

Источник

how to extract nested lists? [duplicate]

While this is probably a duplicate of something, it's not a duplicate of the linked question, which is about creating a list like [["a", "d", "g"], ["a", "d", "h"], ["a", "d", "i"], . ] which is not at all what is wanted here.

3 Answers 3

from itertools import chain list(chain.from_iterable(list_of_lists)) 

@GLHF It's a straightforward question (as well as being over four years old) and doesn't really need more explanation than is in the docs I linked to and the example I gave.

There's a straight forward example of this in the itertools documentation (see http://docs.python.org/library/itertools.html#recipes look for flatten() ), but it's as simple as:

>>> from itertools import chain >>> list(chain(*x)) ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] 

Or, it can be done very easily in a single list comprehension:

>>> x=[["a","b","c"], ["d","e","f"], ["g","h","i","j"]] >>> [j for i in x for j in i] ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] 
>>> from operator import add >>> reduce(add, x) ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] 

An alternative solution to using itertools.chain would be:

>>> li = [["a","b","c"], ["d","e","f"], ["g","h","i","j"]] >>> chained = [] >>> while li: . chained.extend(li.pop(0)) . >>> chained ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] 

EDIT: The above example will consume your original lists while building the new one, so it should be an advantage if you are manipulating very large lists and want to minimise memory usage. If this is not the case, I would consider using itertools.chain more pythonic way to achieve the result.

thank you. i tried using list(itertools.chain(*a)) but this message always comes up TypeError: object of type 'NoneType' has no len() when i tried it on a simple list like the one above it worked fine but when i tried it on a longer more complex one it showed me this error. maybe it has something to do with the favt that there are many empty nested list ([])?

@user1040563 What have you tried exactly? To me both solutions (mine and agf's work fine even with empty sublists. ).

This has higher time complexity than chain or similar solutions because pop(0) is O(n) -- See the "delete item" entry of the "list section of the Python Wiki Time Complexity page. If you wanted to use extend and have the whole thing be linear time, it would be just for sublist in li: chained.extend(li) -- there is no way to do it in linear time from a list in Python without extra storage space (which I assume is what you were trying to avoid).

@agf - Indeed I thought that consuming the original list while building the new one was the "added value" of this solution. Thank you for the link to the time complexity page. I ignored its existence. Interesting! 🙂

I disagree this version being good for very large lists. It's definitely bad if the sublists are short but there are lots of them because of the O(total length * number of sublists) complexity. It's possibly good because of the memory savings if the sublists are long but there aren't very many of them, but keep in mind that the memory usage of a second list is just for the references to the objects in the sublists, no copy of the objects is made, so memory would have to be really tight.

Источник

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