Tue 29 Aug 2006
Python list merging
Posted by dkaz under Python, Programming
One of my Django views required a two-column display, which required simultaneous iteration over two lists.
I didn’t find a clean way to handle this in Django, so I ended up creating a compound list of pairs to back the display.
Here’s my Python code to merge N lists into a list of lists with N entries. There is probably a way to handle this much cleaner - let me know if see how.
'''
merge lists into a list of lists by index
'''
def __merge_lists(*lists):
list_of_lists = []
lengths = [len(list) for list in lists]
for idx in range(max(lengths)):
current_idx_list = []
for list in lists:
if (idx < len(list)):
current_idx_list.append(list[idx])
else:
current_idx_list.append(None)
list_of_lists.append(current_idx_list)
return list_of_lists
