将两个元组合并为一个

时间:2013-05-03 21:50:34

标签: python python-3.x merge tuples

我有两个元组

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

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

我想做这样的事情:

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

结果如下:

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

但是因为我是Python的新手,所以我不确定如何做到这一点。结合两个元组的最佳方法是什么?

2 个答案:

答案 0 :(得分:3)

使用zip和生成器表达式:

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

第一个预期产出:

>>> 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')

第二预期产出:

>>> 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')

使用此ternary expression来处理None值:

>>> x = "foo"
>>> x if x is not None else ""
'foo'
>>> x = None
>>> x if x is not None else ""
''

答案 1 :(得分:1)

尝试拉链功能,如

>>> a = ("string1","string2","string3","string4","string5","string6","string7")
>>> b = ("another string1","another string2",3,None,"another string5",6,7)
>>> [str(x)+str(y) for x,y in zip(a,b)]
['string1another string1', 'string2another string2', 'string33', 'string4None', 'string5another string5', 'string66', 'string77']

如果你想让结果成为元组,你可以这样做:

>>> tuple([str(x)+str(y) for x,y in zip(a,b)])
('string1another string1', 'string2another string2', 'string33', 'string4None', 'string5another string5', 'string66', 'string77')