user8052207
user8052207

Reputation: 33

How to merge two elements in a list in Python

I have a list like this:

list = [(1,'abc'),0.312,(2,'def'),0.122,(1,'abc'),0.999]

I want to merge element(1, 'abc') with 0.312, so the output should like:

list = [(1,'abc',0.312),(2,'def',0.122),(1,'abc',0.999)]

Any one can help me with it? Many thanks!

Upvotes: 2

Views: 1553

Answers (2)

Alok Kumar Singh
Alok Kumar Singh

Reputation: 61

I am new to python. But try to solve this problem.

Here is the code:

>>> list1 = [(1,'abc'),0.312,(2,'def'),0.122,(1,'abc'),0.999]
>>> list_output = list()
>>> t=f=None
>>> l = list()
>>> for i in list1:
...     if type(i) == float:
...        f = i
...     if type(i) == tuple:
...        t = i
...     if t and f:
...        for j in t:
...           l.append(j)
...        l.append(f)
...        list_output.append(tuple(l))
...        l = []
...        t = f = None
... 
>>> 
>>> 
>>> list_output
[(1, 'abc', 0.312), (2, 'def', 0.122), (1, 'abc', 0.999)]

Please let me know if you get best solution

Upvotes: 0

Moses Koledoye
Moses Koledoye

Reputation: 78556

Use a list comprehension to build the new tuple after zipping your list items in twos:

l = [i+(j,) for i, j in zip(lst[::2], lst[1::2])]
print(l)
# [(1, 'abc', 0.312), (2, 'def', 0.122), (1, 'abc', 0.999)]

Upvotes: 7

Related Questions