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']
Extracting first and last element from sublists in nested list
You have the right idea. If your list inside list is only one layer deep, you can access the first and last elements with a list comprehension and -1 indexing like you were trying to do:
a = [[sublist[0],sublist[-1]] for sublist in x]
Output:
>>> a
[[1, 3], [4, 6], [7, 9]]
Get first item of every sublist of list in Python
To capture the first elements into a variable, you can use a list comprehension like:
Code:
data = {
'ID': [[310.5, 1.1612828],
[310.0, 15.0],
[310.0, 2.9755309],
[309.5, 30.0]]
}
variable = [x[0] for x in data['ID']]
print(variable)
Results:
[310.5, 310.0, 310.0, 309.5]
How to extract a sublist by the value of the first element from a nested list
my_list = [
['nom', 'N', 'eye'],
['acc', 'E', 'computer'],
['dat', 'C', 'screen']
]
my_input = input("Enter first string to find: ")
for lis in my_list:
if lis[0] == my_input:
print(lis)
break
Output:
Enter variable name: nom
['nom', 'N', 'eye']
Select first two elements of each sublist in a list
Use a list comprehension to apply the same slice to each sublist:
b = [l[:2] for l in a]
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
Extract the first, second, third , … sub-element from a list in R and store as list
Yes
lapply(1:15, function(i) sapply(list_data, '[', i))
Counting the frequency of the first element of a list within a list
Just split your task into a two parts:
- Retrieve first element from each inner list;
- Sort elements in descending order by number of occurrences.
You can easily find an answer of each of this problem on Stack Overflow:
- Extract first item of each sublist;
- Sorting a List by frequency of occurrence in a list.
Even question you've additionally answered in comments already have been answered: How to access the first element or number in counter using Python.
You should make some research efforts before asking question otherwise you waste both yours time and time of users who will answer your question.
Anyway, let's go back to your problem.
To get first value of inner list you should iterate over outer list and retrieve first element from every item. With simple
for
loop it will look like this:source_list = [[4, 2, 1, 3], [4, 3, 1, 2], [4, 3, 1, 2],
[1, 3, 4, 2], [2, 3, 4, 1], [2, 1, 3, 4]]
first_items_list = []
for inner_list in source_list:
first_items_list.append(inner_list[0])You can also use list comprehension:
source_list = [[4, 2, 1, 3], [4, 3, 1, 2], [4, 3, 1, 2],
[1, 3, 4, 2], [2, 3, 4, 1], [2, 1, 3, 4]]
first_items_list = [inner_list[0] for inner_list in source_list]Now we have to find max element in list of first items by frequency. To not reinvent the wheel you can apply
collections.Counter
and specifically it'sCounter.most_common()
method.To initialize
Counter
you need to passfirst_items_list
generated in code above toCounter()
constructor. Then you need to callCounter.most_common()
and pass1
to arguments as you need just most common element:from collections import Counter
...
counter = Counter(first_items_list)
item, number_of_occurrences = counter.most_common(1)[0]
To simplify the code you can change list comprehension to generator expression and pass it directly into Counter
constructor:
source = [[4, 2, 1, 3], [4, 3, 1, 2], [4, 3, 1, 2],
[1, 3, 4, 2], [2, 3, 4, 1], [2, 1, 3, 4]]
print("Most common:", Counter(inner[0] for inner in source).most_common(1)[0][0])
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
Related Topics
How to Cross Compile Python Interpreter for Windows Under Linux
Bring the Current Python Program to Background
How to Make a Discontinuous Axis in Matplotlib
Match a Whole Word in a String Using Dynamic Regex
How to Set Python's Default Version to 3.X on Os X
Pg_Config Executable Not Found
Beyond Top Level Package Error in Relative Import
How to Find All the Subclasses of a Class Given Its Name
Beautifulsoup Grab Visible Webpage Text
Http Requests and JSON Parsing in Python
How to Tail a Log File in Python
How Does Asyncio Actually Work
How to Execute a Program from Python? Os.System Fails Due to Spaces in Path
Append Multiple Pandas Data Frames at Once
How Exactly Does a Generator Comprehension Work
Problem Running Python from Crontab - "Invalid Python Installation"