Home > database >  Python remove tuples and merge the two values from tuples inside them to one item
Python remove tuples and merge the two values from tuples inside them to one item

Time:04-13

I have list similar to this:

[('name', ''),('season', ''),('company', ''),('date', ''),('mean value', 1),('mean value', 2),('mean value', 3), ('mean value', 4)]

I would like to get rid of the tuples and to merge between the two values if exists, to get the following list:

['name','season','company','date','mean value 1','mean value 2', 'mean value 3', 'mean value 4']

I'm not sure how to do this, looking for ways to do this efficiently.

CodePudding user response:

If you want to add in a space (mean value 4):

[f"{a} {b}".strip() for a, b in lst]

If you don't need a space ('mean value4'):

[f"{a}{b}" for a, b in lst]

Note: This answer only works for tuples of length 2

CodePudding user response:

list(map(lambda t: " ".join(map(lambda x: str(x), t)), mylist))

or

[" ".join(map(lambda x: str(x), t)) for t in mylist]

CodePudding user response:

I think this code is easy to understand and works.

tup = [('name', ''),('season', ''),('company', ''),('date', ''),('mean value', 1),('mean value', 2),('mean value', 3), ('mean value', 4)]

def func(value):
    string = ''
    for a in value:
        string  = str(a)
        string =' '
    return string.strip()
result = list(map(func,tup))

CodePudding user response:

How about if-else in a list comprehension

stuff = [('name', ''),('season', ''),('company', ''),('date', ''),('mean value', 1),('mean value', 2),('mean value', 3), ('mean value', 4)]

joined = [f'{a} {b}' if b else a for a, b in stuff]
print(joined)

CodePudding user response:

Check this:

test_list = [('name', ''),('season', ''),('company', ''),('date', ''),('mean value', 1),('mean value', 2),('mean value', 3), ('mean value', 4)]
new_list = []
for item in test_list:
    new_list.append(' '.join(map(str,item)).strip())
  • Related