I have a list that contain the column indexes as follows:
list1 = [0 ,2]
Another list of list would contain the file contents of a csv file as follows:
list2=[["abc", 1, "def"], ["ghi", 2, "wxy"]]
What can be the best way to create a new list that would only contain the values from list2
with the column numbers that are contained in list1
i.e.
newList = [["abc", "def"], ["ghi", "wxy"]]
I am having a hard time creating the sublists
Data Visualization using R Programming Therefore, we can use lapply function for this extraction. For example, if we have a list called LIST that store two data frames then column 3 of each data frame can be extracted by using the command lapply(LIST,"[",3).
Using numpy.ndarray.tolist() From the dataframe we select the column “Name” using a [] operator that returns a Series object and uses Series. Values to get a NumPy array from the series object. Next, we will use the function tolist() provided by NumPy array to convert it to a list.
$ operator in R is used to extract a specific part of data or access a variable in a dataset. We can pass data frame column to a list by using $ operator. The columns to be selected are to be passed with dataframe name separated by $.
You can use List Comprehension
: -
newList = [[each_list[i] for i in list1] for each_list in list2]
If you are happy with a list of tuples, you can use operator.itemgetter
import operator
list1 = [0,2]
my_items = operator.itemgetter(*list1)
new_list = [ my_items(x) for x in list2 ]
(or you could use map
here):
new_list = map(my_items, list2)
and as a 1 liner:
new_list = map(operator.itemgetter(*list1), list2)
operator.itemgetter
probably has a slight performance advantage over nested list-comprehensions, but it's likely to be small enough that it's not worth worrying about.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With