Python list help
Go to solution
Solved by straight_stewie,
In a single list comprehension:
test_list = ["65uyr, the, quick, brown", "h213, fox jumps over"] final_list = [i.split(",")[j] for i in test_list for j in range(1, len(i.split(",")))]
Anything that can be written as a series of nested loops, each loop only containing another loop except for the final loop which can contain some action that appends some items to another list and is able to be written in a single statement can be converted to a list comprehension.
For example:
test_list = ["65uyr, the, quick, brown", "h213, fox jumps over"] tmp = [] for i in test_list: for j in range(1, len(i.split(","))): tmp.append(i.split(",")[j])
becomes:
test_list = ["65uyr, the, quick, brown", "h213, fox jumps over"] tmp = [i.split(",")[j] for i in test_list for j in range(1, len(i.split(",")))]
The algorithm is quite simple, assuming that your loop chain is already written in the form described above:
- Take the final statement of the for loop chain, and make it the first statement in the list comprehension.
- Write the loops in order from top to bottom.
Disclaimer: It may be possible to make list comprehensions from nested loops that do not conform to the above description. I haven't experimented enough to find out yet.
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now