Select First Element of Nested List

Select first element of nested list

Not much of a shortcut, but you can do this:

lapply(x, `[[`, 1)
# [[1]]
# [1] 1
#
# [[2]]
# [1] 3
#
# [[3]]
# [1] 5

C# linq how to get all the first elements of a nested dynamic list?

Proper and efficient way of doing this is as follows:

mainList.Select(subList => subList?.First()).OfType<dynamic>();

This will take care of null lists and null elements

If you want to select all the elements of sublists try following

mainlist.Select(subList => subList).OfType<List<dynamic>>();

This will only take care of null lists

Selecting all first element of a nested list / array

You can use zip with unpacking:

max_peaksIdx, max_peaksVal = zip(*peaks)

Output:

max_peaksIdx
# (313, 695, 996, ...)
max_peaksVal
# (0.7608371709999999, 0.6970320329999999, 0.652950446,...)

If you have to construct numpy array:

arr = np.array(peaks)
max_peaksIdx, max_peaksVal = arr[:, 0], arr[:, 1]

But zip is about 9x faster:

%timeit max_peaksIdx, max_peaksVal = zip(*peaks)
# 1.19 µs ± 91.5 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

%%timeit
arr = np.array(peaks)
max_peaksIdx, max_peaksVal = arr[:, 0], arr[:, 1]
# 10 µs ± 120 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

Extract first item of each sublist

Using list comprehension:

>>> lst = [['a','b','c'], [1,2,3], ['x','y','z']]
>>> lst2 = [item[0] for item in lst]
>>> lst2
['a', 1, 'x']

Extract the first item of the list from nested lists

Try :

dt$col2 <-sapply(dt$col1 , "[", 1)

(The elements of your lists are not lists, just vectors, so one bracket is fine)

EDIT :

For a column inside a data.table :

 dt$col2 <- sapply(dt$col1,function(x){sapply(x,'[',1)})

Select the first element from the first list, the second element from the second list, and so on, in a nested list

You can use the sapply using the length of the list and the function to subset the list as below:

sapply(1:length(lst), function(x) lst[[x]][[x]])

Python: first element in a nested list

Your solution returned [[None, None, None], [None, None, None], [None, None, None]] because the method append returns the value None. Replacing it by t[0] should do the trick.

What you're looking for is:

R = [[t[0] for t in l] for l in L]

First element in list/nested lists

You can try

ls[0][0] if isinstance(ls[0], list) else ls[0]

This will return the ls[0][0] if ls containing a list in the first value else the first value of the ls.



Related Topics



Leave a reply



Submit