Here is how you would do this with a nested list comprehension:
[[float(y) for y in x] for x in l]
This would give you a list of lists, similar to what you started with except with floats instead of strings.
If you want one flat list, then you would use
[float(y) for x in l for y in x]
Note the loop order - for x in l comes first in this one.
Does anybody else just not like the syntax for nested one-line list comprehension?
How can I use a nested list comprehension in Python to process a nested list? - TestMu AI Community
Is there an official name for a list comprehension with multiple for clauses?
Help understanding nested list comprehensions
Videos
Here is how you would do this with a nested list comprehension:
[[float(y) for y in x] for x in l]
This would give you a list of lists, similar to what you started with except with floats instead of strings.
If you want one flat list, then you would use
[float(y) for x in l for y in x]
Note the loop order - for x in l comes first in this one.
Here is how to convert nested for loop to nested list comprehension for your example:
newList = []
for x in l:
for y in x:
newList.append(float(y))
newList = [
float(y)
for x in l
for y in x
]
Some other examples
students = [
{"name": "John", "age": 18, "friends": ["Alice", "Bob"]},
{"name": "Alice", "age": 19, "friends": ["John", "Doe"]},
]
# Normal for loop
friends = []
for student in students:
for friend_name in student["friends"]:
friends.append(friend_name)
# List comprehension
friends = [
friend_name
for student in students
for friend_name in student["friends"]
]
For your case, if you want a flat list, it will be something like this.
new_list = [float(y) for x in l for y in x]
Another interesting example with if conditions in the mix:
school_data = [
{
"students": [
{"name": "John", "age": 18, "friends": ["Alice", "Bob"]},
{"name": "Alice", "age": 19, "friends": ["John", "Bob"]},
],
"teacher": "Mr. Smith",
},
{
"students": [
{"name": "Sponge", "age": 20, "friends": ["Bob"]},
],
"teacher": "Mr. tom",
},
]
result = []
for class_dict in school_data:
for student_dict in class_dict["students"]:
if student_dict["name"] == "John" and student_dict["age"] == 18:
for friend_name in student_dict["friends"]:
if friend_name.startswith("A"):
result.append(friend_name)
And here is the listcomp version
result = [
friend_name
for class_dict in school_data
if class_dict["teacher"] == "Mr. Smith"
for student_dict in class_dict["students"]
if student_dict["name"] == "John" and student_dict["age"] == 18
for friend_name in student_dict["friends"]
if friend_name.startswith("A")
]
# result => ['Alice']
Suppose I want to do some list comprehension:
new_list = [x*b for x in a]
Notice how you can easily tell what the list comprehension is doing by just reading left to right - i.e., "You calculate the product of x and b for every x in a."
Now, consider nested list comprehension. This code here which flattens a list of lists into just a single list:
[item for sublist in list_of_lists for item in sublist]
Now, read this line of code:
[i*y for f in h for i in f]
Is this not clearly more annoying to read than the first line I posted? In order to tell what is going on you need to start at the left, then discern what i is all the way at the right, then discern what f is by going back to the middle.
If you wanted to describe this list comprehension, you would say: "Multiply i by y for every i in every f in h." Hence, this feels much more intuitive to me:
[item for item in sublist for sublist in list_of_lists] [i*y for i in f for f in h]
In how I have it, you can clearly read it left to right. I get that they were trying to mirror the structure of nested for loops outside of list comprehension:
for sublist in list_of_lists:
for item in sublist:
item... however, the way that list comprehension is currently ordered still irks me.
Has anyone else been bothered by this?
I know the top comment is going to be ~ Never reduce lines of code at the expense of readability; I wholeheartedly agree. Unfortunately, at my work, I'm sorting through quite a few nested list comprehensions and I'm having a hard time making sense of their structure.
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] flattened_list = [item for sublist in nested_list for item in sublist] print(flattened_list) >>>> [1, 2, 3, 4, 5, 6, 7, 8, 9]
What really trips me up is the for item in sublist after nested_list is referenced. If nested lists were 3 layers deep instead of 2, I have no idea what that should look like. Which makes me feel that I can memorize the pattern, but I don't really understand its rules.