Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge two tuples into one

I have two tuples

("string1","string2","string3","string4","string5","string6","string7")

and

("another string1","another string2",3,None,"another string5",6,7)

I would like to do something like this:

("string1another string1","string2another string2","string33","string4","string5another string5","string66","string77").

It would also be ok with a result like:

("string1another string1","string2another string2","string33","string4None","string5another string5","string66","string77")

But since I'm new to Python I'm not sure on how do that. What is the best way of combining the two tuples?

like image 709
Mattias Avatar asked Dec 28 '25 09:12

Mattias


1 Answers

Use zip and a generator expression:

>>> t1=("string1","string2","string3","string4","string5","string6","string7")
>>> t2=("another string1","another string2",3,None,"another string5",6,7)

First expected output:

>>> tuple("{0}{1}".format(x if x is not None else "" ,
                             y if y is not None else "") for x,y in zip(t1,t2))
('string1another string1', 'string2another string2', 'string33', 'string4', 'string5another string5', 'string66', 'string77')

Second expected output:

>>> tuple("{0}{1}".format(x,y) for x,y in zip(t1,t2)) #tuple comverts LC to tuple
('string1another string1', 'string2another string2', 'string33', 'string4None', 'string5another string5', 'string66', 'string77')

Use this ternary expression to handle the None values:

>>> x = "foo"
>>> x if x is not None else ""
'foo'
>>> x = None
>>> x if x is not None else ""
''
like image 100
Ashwini Chaudhary Avatar answered Dec 31 '25 00:12

Ashwini Chaudhary



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!