Jump to content

Python list help

Yellow_
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:

  1. Take the final statement of the for loop chain, and make it the first statement in the list comprehension.
  2. 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.

Hi

I'm trying to learn python over the weekends andfound myself at a roadblock

 

I have a for loop that works with a list that I want to turn into a comprehension list, but I want to nest for loops inside the comprehension list. I have no idea how to do that

 

I'm mainly looking at the 4th block of code where i end with appending y into singles 

 

singles = []

splitting = [i.split(",") for i in physical_activity_data]

for i in splitting:
    del i[0]

for i in splitting:
    for y in i:
        y.split(",")
        singles.append(y)

formatted = [i.lower().strip() for i in singles]

 

Thanks!!

Link to comment
Share on other sites

Link to post
Share on other sites

Pardon, but could you restate what you're trying to do with the "Singles" list? Are you trying to organize it by a certain aspect of text (Organize it by parts that contain a character like "a") or simply split it by the comma?

 

Edit: If you want to next loops, just use a different letter (Ex. j instead of i).

 

Do you have a list named "i"? If not, then why is it "i.split"?

Fan Comparisons          F@H          PCPartPicker         Analysis of Market Trends (Coming soon? Never? Who knows!)

Designing a mITX case. Working on aluminum prototypes.

Open for intern / part-time. Good at maths, CAD and airflow stuff. Dabbled with Python.

Please fill out this form! It helps a ton! https://linustechtips.com/main/topic/841400-the-poll-to-end-all-polls-poll/

Link to comment
Share on other sites

Link to post
Share on other sites

3 minutes ago, Imbellis said:

Pardon, but could you restate what you're trying to do with the "Singles" list? Are you trying to organize it by a certain aspect of text (Organize it by parts that contain a character like "a") or simply split it by the comma?

oh, sorry. I should have included an example from the list.

 

Basically, the raw list code looks like this:

 

list = ["65uyr, the, quick, brown", "h213, fox jumps over"]

 

its much longer than that, but thats the gist of it .

 

so singles is there to home each of the values after I split each index into smaller ones

Link to comment
Share on other sites

Link to post
Share on other sites

Just now, Yellow_ said:

Basically, the raw list code looks like this:


list = ["65uyr, the, quick, brown", "h213, fox jumps over"]

 

so singles is there to home each of the values after I split each index into smaller ones

1

So what are you trying to do with that list? Remove terms with numbers? I'm totally willing to help - I just need to figure out what you're trying to do.

Fan Comparisons          F@H          PCPartPicker         Analysis of Market Trends (Coming soon? Never? Who knows!)

Designing a mITX case. Working on aluminum prototypes.

Open for intern / part-time. Good at maths, CAD and airflow stuff. Dabbled with Python.

Please fill out this form! It helps a ton! https://linustechtips.com/main/topic/841400-the-poll-to-end-all-polls-poll/

Link to comment
Share on other sites

Link to post
Share on other sites

1 minute ago, Imbellis said:

So what are you trying to do with that list? Remove terms with numbers? I'm totally willing to help - I just need to figure out what you're trying to do.

Yeah sorry, I'm totally new to most programming stuff so I'm just trying to wrap my head around everything

 

So I want to take out the first little bit of data per index, eg. the "65uyr" and "h213". I also want to get "quick, brown" to be individual list elements instead of in a string.

So the lines I have in the original post succeeds in that, I know its pretty ugly, but it works

 

Now I just want to know how to turn for loops such as this one:

for i in splitting:
    for y in i:
        y.split(",")
        singles.append(y)

into a list comprehension, if its possible

Link to comment
Share on other sites

Link to post
Share on other sites

Something along this line for the splitting?

StringList = ["65uyr, the, quick, brown", "h213, fox jumps over", "Th15 is just to test things"]
FirstInSubList = []
RemainingElements = []

for i in range(len(StringList)):  # Iterates through StringList on string at a time
    FirstInSubList.append(StringList[i].split()[0])  # Splits StringList(i) and takes the first item in list
    RemainingElements.append(StringList[i].split()[1:])  # Splits StringList(i) and takes items after the first

print(FirstInSubList)
print(RemainingElements)

After this, what do you want to do with the items? Are you wanting to re-merge it back into a single list? If so:

for i in range(len(StringList)):
    FirstInSubList.append(StringList[i].split()[0])  # Splits StringList and takes the first item in list (Index 0)
    Cache = StringList[i].split()[1:]  # Sets Cache as each split - removing the first element.
    # print(Cache)
    for j in range(len(Cache)):  # Iterates through each element in Cache. Uses "j" As position in list.
        RemainingElements.append(Cache[j])  # Appends each position in Cache to a single list.

 

Fan Comparisons          F@H          PCPartPicker         Analysis of Market Trends (Coming soon? Never? Who knows!)

Designing a mITX case. Working on aluminum prototypes.

Open for intern / part-time. Good at maths, CAD and airflow stuff. Dabbled with Python.

Please fill out this form! It helps a ton! https://linustechtips.com/main/topic/841400-the-poll-to-end-all-polls-poll/

Link to comment
Share on other sites

Link to post
Share on other sites

#Although:
  
for i in StringList # Iterates through StringList with "i" instantly being set to StringList.
	FirstItem.append(i.split()[0])
                     
#and 

for i in range(len(StringList)) #Iterates through StringList using "i" as the index (Position in list). Sets I as numberic.
	FirstItem.append(StringList[i].split()[0])
                     
#effectively do the same thing, I usually recommend peope use the latter.
#I think it makes it easier to traceback where "FirstItem" is getting the data from.

 

Fan Comparisons          F@H          PCPartPicker         Analysis of Market Trends (Coming soon? Never? Who knows!)

Designing a mITX case. Working on aluminum prototypes.

Open for intern / part-time. Good at maths, CAD and airflow stuff. Dabbled with Python.

Please fill out this form! It helps a ton! https://linustechtips.com/main/topic/841400-the-poll-to-end-all-polls-poll/

Link to comment
Share on other sites

Link to post
Share on other sites

46 minutes ago, Imbellis said:

 

Okay, those all make much more sense.

 

I was unaware of some of those methods (not like programming methods but like dictionary definition)

 

Thanks so much, I really appreciate it

 

Link to comment
Share on other sites

Link to post
Share on other sites

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:

  1. Take the final statement of the for loop chain, and make it the first statement in the list comprehension.
  2. 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.

ENCRYPTION IS NOT A CRIME

Link to comment
Share on other sites

Link to post
Share on other sites

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 account

Sign in

Already have an account? Sign in here.

Sign In Now

×