2013-05-03 72 views
3

我有两个元合并两个元为一个

("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,我不确定那是怎么做的。组合这两个元组的最佳方式是什么?

回答

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 "" 
'' 
+0

+1,但是...为什么你传递一个listcomp为'元组'而不是生成器表达式?它使读起来稍微困难一些(更多的parens /括号/等跟踪),并在大的情况下浪费内存,在极小的情况下2.x性能的好处几乎无关紧要。 – abarnert 2013-05-03 22:16:36

+0

@abarnert你说得对,性能是我有时更喜欢列表理解而不是生成器表达的唯一原因。从性能至关重要的节目比赛中我选择了这种坏习惯。 – 2013-05-03 22:24:02

+0

难道不是:x if x else“”? – dansalmo 2013-05-03 22:44:44

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

这几乎是正确的,但''string4“+ None'是一个'TypeError',而不是''string4None”'。 (如果你解决了这个问题,这与Ashwini Chaudhary之前的回答有什么不同?) – abarnert 2013-05-03 22:17:17

+0

@abarnert askers说“string4None”没问题。在连接两个部分之前,我使用了str()函数。所以它应该运作良好。 – Sheng 2013-05-03 22:45:04