changing from tuple to list and vice versa
how could i change [('a'开发者_运维知识库, 1), ('c', 3), ('b', 2)]
to ['a',1,'c',3,'b',2]
and vice versa?
Thanks
Going in the first direction from [('a', 1), ('c', 3), ('b', 2)]
to ['a',1,'c',3,'b',2]
is flattening a list. Taking the accepted answer from there and modifying for this example:
>>> L = [('a', 1), ('c', 3), ('b', 2)]
>>> list(itertools.chain(*L))
['a', 1, 'c', 3, 'b', 2]
This uses itertools.chain
which is a nice tool from itertools
that flattens sequences quite nicely.
Going the opposite way is zipping:
>>> L = ['a', 1, 'c', 3, 'b', 2]
>>> zip(L[0::2], L[1::2])
[('a', 1), ('c', 3), ('b', 2)]
zip
takes two lists and combines list 1's first element with list 2's first element in a tuple, and so on down the lengths of the list. So in this one, we basically take the even-indexed elements as our first list (L[0::2]
), and then the odd-indexed elements as our second (L[1::2]
)
Here it's my take on it (assuming a contains first list and b second):
b = []
for i in a:
b.extend(i)
And reverse:
c = []
for i in range(0, len(b) - 1, 2):
c.append((b[i], b[i+1]))
L = [('a', 1), ('c', 3), ('b', 2)]
flat = [x for p in L for x in p]
assert flat == ['a', 1, 'c', 3, 'b', 2]
it = iter(flat)
L2 = zip(it, it)
assert L2 == L
print "Success"
There are already plenty of correct answers here, so this is just a reminder not to use sum() to flatten lists as although it looks like a neat solution unfortunately the performance is quadratic
In [1]: L=[('a',x) for x in range(10)]
In [2]: timeit sum(L,())
100000 loops, best of 3: 2.78 us per loop
In [3]: L=[('a',x) for x in range(100)]
In [4]: timeit sum(L,())
10000 loops, best of 3: 108 us per loop
In [5]: L=[('a',x) for x in range(1000)]
In [6]: timeit sum(L,())
100 loops, best of 3: 8.02 ms per loop
精彩评论