简体   繁体   中英

Nested list in list comprehension to for loop

I am taking a class to learn python. We are in the section covering list comprehension and I am having a hard time understanding what is happening in one of the examples. I am trying to convert it back to a for loop to understand what is happening but and I am running into an issue.

Example: 1 This I am able to convert into a FOR loop just fine. The output is the same


my_list1 = [ x * y for x in [20, 40, 60] for y in [2, 4, 6]]
print('My list 1', my_list1)

my_list2 = []

for x in [20, 40, 60]:
    for y in [2, 4, 6]:
        my_list2.append(x*y)

print(my_list2)

OUTPUT

My list 1 [40, 80, 120, 80, 160, 240, 120, 240, 360]

My list 2 [40, 80, 120, 80, 160, 240, 120, 240, 360]


Example 2: I am having a problem with converting into a FOR loop. My output is different. I don't know how to get a list to output within a list. The second set of [] is what is throwing me off. I don't know where they need to go when converting into to a FOR loop to get a list within as list as a result.

Can you someone explain what I am doing wrong?

my_list3 = [[x * y for x in [20, 40, 60]] for y in [2, 4, 6]]
print('My list 3', my_list3)

my_list4 = []

for x in [20, 40, 60]:
    for y in [2, 4, 6]:
        my_list4.append([x*y])


print('My list4', my_list4)

OUTPUT

My list 3 [[40, 80, 120], [80, 160, 240], [120, 240, 360]]

My list4 [[40], [80], [120], [80], [160], [240], [120], [240], [360]]

I see that it's more complicated because they want you to have a list of lists in your output. Each element you add to my_list4 must be a list itself.

If the assignment is to remove all list comprehensions, you will have to build up a sublist one item at a time, and then add the sublist to the parent list. Like this:

for x in [20, 40, 60]:
  sublist = []  # make an empty sublist
  for y in [2, 4, 6]:
    sublist.append(x*y)  # put a single value into the sublist
  my_list4.append(sublist)  # add the completed sublist onto the parent list

While I prefer the above approach for clarity, you can also avoid making the temporary list by adding the empty sublist to the parent list in advance, and constantly referring to it while you add values:

for x in [20, 40, 60]:
  my_list4.append([])  # append the empty sublist to the parent list
  for y in [2, 4, 6]:
    my_list4[-1].append(x*y)  # use [-1] to reference the last item
                              # in my_list4, which is the current sublist.

Your attempt was making a one-element list for each combination of x and y (the square brackets around each individual value show you this).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM