2014-10-09 165 views
-1

所以我有一個下面的代碼:我如何從數組中的列表創建兩個列表?

thing = [ ['Promotion not applied', 'Buy1, get 1 for FOR $4.50', '(', 'details', ')'],  [], ['Promotions Applied:', 'BUY 1, GET 1 FOR $4.50', '(', 'details', ')'] ] 

以便它遍歷一個列表,我想創建適用於promo_applied和promo_not兩個新的列表:

所以回報是:

promo_applied=["promotions applied", 'Buy1, get 1 for FOR $4.50'] 
promo_not_applied = ["promotion not applied", 'Buy1, get 1 for FOR $4.50'] 
+0

而且?有什麼問題?你已經有了這兩個列表(加上一些其他的東西),那麼你真正的問題是什麼?你知道如何訪問列表元素嗎?順便說一下,這感覺非常[XY-ish](http://meta.stackexchange.com/q/66377/214517)對我來說 - 這些列表來自哪裏? – 2014-10-09 23:25:48

+0

'thing'列表是否總是包含3個元素? 'thing'中是否有多於一個可能出現的以''沒有應用促銷''或''應用促銷'開頭的列表? – 2014-10-09 23:27:03

+0

我認爲你應該退一步,更詳細地設計你的程序。尤其是,您應該瞭解可用於表示每次促銷的類和對象。 – 2014-10-16 23:15:24

回答

0
thing = [ ['Promotion not applied', 'Buy1, get 1 for FOR $4.50', '(', 'details', ')'],  [], ['Promotions Applied:', 'BUY 1, GET 1 FOR $4.50', '(', 'details', ')'] ] 

promo_applied, _, promo_not_applied = map(lambda s:s[:2], thing) 
0
thing = [['Promotion not applied', 'Buy1, get 1 for FOR $4.50', '(', 'details', ')'],[],['Promotions Applied:', 'BUY 1, GET 1 FOR $4.50', '(', 'details', ')']] 

promo_applied = [_[:2] for _ in thing if 'Promotions Applied:' in _] 
promo_not_applied = [_[:2] for _ in thing if 'Promotion not applied' in _]