>>> a=["a"]*4
>>> a
['a', 'a', 'a', 'a']
>>> b=range(4)
>>> b
[0, 1, 2, 3]
>>> c = [range(4,8), range(9,13), range(14,18), range(19,23)]
>>> c
[[4, 5, 6, 7], [9, 10, 11, 12], [14, 15, 16, 17], [19, 20, 21, 22]]
>>>
>>> result = map(lambda x,y:[x,y],a,b)
>>> map(lambda x,y:x.extend(y),result,c)
>>> result = map(tuple, result)
>>> result # desired output:
[('a', 0, 4, 5, 6, 7), ('a', 1, 9, 10, 11, 12), ('a', 2, 14, 15, 16, 17), ('a', 3, 19, 20, 21, 22)]
>>>
>>> try_test = zip(a,b,c)
>>> try_test # NOT DESIRED: leaves me with the list within the tuples
[('a', 0, [4, 5, 6, 7]), ('a', 1, [9, 10, 11, 12]), ('a', 2, [14, 15, 16, 17]), ('a', 3, [19, 20, 21, 22])]
I was wondering whether anyone has a more succinct way to do the “result”?
For a fully general approach to this problem, you might consider using one of the many variations on
flattenyou can find here, whereflattenis a function that takes an arbitrarily nested iterable of iterables and returns a flat list of the items contained therein.Then just map
flattenover the zipped values ofa, b, cand convert to tuple.Or even more succinctly, modify
flattento accept an arbitrary argument list and return a tuple. Then all you need ismap:If this is a one-off problem, the above approach is probably more trouble than it’s worth. But if you’ve already defined
flattenfor other purposes, or if you’re doing this frequently, the above could save you a lot of trouble!Otherwise, just for the fun of it, here’s a variation on nneonneo‘s answer that I like: