简体   繁体   中英

How to create lists using for loop in pyhton

What I want to get is

[a][b][c]

Getting each index from an array a=[a,b,c]. I'm using this to approach a value in dictionary.

All I could find was.append() but this returns me [a,b,c] not [a][b][c]

This is the function that I made

Def loop():
   Newlist = []
   for i in a:
      Newlist.append(i)
   return Newlist
     

You want to append a list of one value, not a single value. ie

>>> new_list = []
>>> new_list.append([1])
>>> new_list.append([2])
>>> new_list.append([3])
[[1], [2], [3]]

So in the method you'd do something like this:

def loop():
    new_list = []
    for i in a:
        new_list.append([i])
    return new_list

Try this:

Create a new list inside the loop that gets reset each time, add your variable, then add the new list to the parent list.

You can also grab individual lists from the parent list using the following: Newlist[1]

Def loop():
   Newlist = []
   for i in a:
      temp_list = []
      temp_list.append(I)
      Newlist.append(temp_list)
   return Newlist

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