Python: merge nested lists

Use the power of the zip function and list comprehensions: list1 = [(‘a’, ), (‘b’, ‘c’), (‘d’, ‘e’), (‘f’, ‘g’, ‘h’) ] list2 = [(‘p’, ‘q’), (‘r’, ‘s’), (‘t’, ), (‘u’, ‘v’, ‘w’) ] print [a + b for a, b in zip(list1, list2)]

How to use to iterate over a nested list?

What you need is to nest another <ui:repeat> tag in your outer iteration: <ui:repeat value=”#{bean.listOfA}” var=”a”> … <ui:repeat value=”#{a.listOfB}” var=”b”> … </ui:repeat> </ui:repeat> The only thing left that is worth noting is that nested <ui:repeat> tags used to have problems with state management until Mojarra 2.1.15 version (details in jsf listener not called inside nested … Read more

Replace list of list with “condensed” list of list while maintaining order

Here’s a brute-force approach (it might be easier to understand): from itertools import chain def condense(*lists): # remember original positions positions = {} for pos, item in enumerate(chain(*lists)): if item not in positions: positions[item] = pos # condense disregarding order sets = condense_sets(map(set, lists)) # restore order result = [sorted(s, key=positions.get) for s in sets] … Read more

Flatten an irregular (arbitrarily nested) list of lists

Using generator functions can make your example easier to read and improve performance. Python 2 Using the Iterable ABC added in 2.6: from collections import Iterable def flatten(xs): for x in xs: if isinstance(x, Iterable) and not isinstance(x, basestring): for item in flatten(x): yield item else: yield x Python 3 In Python 3, basestring is … Read more

why can’t I change only a single element in a nested list in Python [duplicate]

A strange behaviour indeed, but that’s only because * operator makes shallow copies, in your case – shallow copies of [0, 0, 0] list. You can use the id() function to make sure that these internal lists are actually the same: out=[[0]*3]*3 id(out[0]) >>> 140503648365240 id(out[1]) >>> 140503648365240 id(out[2]) >>> 140503648365240 Comprehensions can be used … Read more