2013-05-03 113 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