This is a question regarding best coding practices. Suppose I have to populate a list of unknown length; usually I just initialize the list with myList = []
, but I feel like this is a poor way of doing this. I often end up with chunks of code that look like this:
list1 = []
list2 = []
list3 = []
for a,b,c in zip(x,y,z):
list1.append(a)
list2.append(b)
list3.append(c)
I realize in the example you can initialize this lists to the correct length, in fact you can just use x,y,z
as they are. My question is regarding a situation in which you don't necessarily know the length of the lists. In my opinion, having to use three lines to initialize this lists is clunky; what do you guys thing? Thanks for any input!
No need for anything clever:
list1 = list(x)
list2 = list(y)
list3 = list(z)
Use a list of lists:
lol = [[], [], []]
for items in zip(x, y, z):
for i, item in enumerate(items):
lol[i].append(item)
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.