2010-05-29 56 views
1

這可能是一個非常愚蠢的問題,但是,考慮到底部的示例代碼,我將如何獲得保留元組的單個列表?部分展平列表

(我看了itertools但它變平的一切。)

我目前得到的是:

( '身份證',20 '整')
( '公司名稱' ,'50','text')
[('focus',30,'text'),('fiesta',30,'text'),('mondeo',30,'text'),('puma ',30,'text')]
('contact',50,'text')
('email',50,'text')

相反,我需要一個單級列表:

( '身份證',20 '整')
( '公司名稱',50, '文本')
(」焦點,30, '文本')
( '嘉年華',30, '文本')
( '蒙迪歐',30, '文本')
( '美洲獅',30, '文本')

('contact',50,'text')
( '電子郵件',50, '文本')

代碼:

def getproducts(): 
    temp_list = [] 

    product_list = ['focus', 'fiesta', 'mondeo', 'puma'] 
    # usually this would come from a db 

    for p in product_list: 
     temp_list.append((p, 30, 'text')) 
    return temp_list 

def createlist():  
    column_title_list = (
     ("id", 20, "integer"), 
     ("companyname", 50, "text"), 
     getproducts(), 
     ("contact", 50, "text"), 
     ("email", 50, "text"), 
    ) 
    return column_title_list 

for item in createlist(): 
    print item 

回答

2

你能使其成爲

[[("id",20,"integer")], 
[("companyname",50,"text")], 
getproducts(), 
...] 

?如果是這樣,你只需要連接列表。

return sum(column_title_list, []) 

你也可以使用

return [("id",20,"integer"),("companyname",50,"text")] + getproducts() + ... 
+0

嗨KennyTM和Ofri。你的答案都非常相似。謝謝。我會看看這樣做。 – alj 2010-05-29 14:09:25

0
def createlist():  
    column_title_list = [ ("id",20,"integer"), 
          ("companyname",50,"text") ] 
    column_title_list.extend(getproducts()) 
    column_title_list.extend([ ("contact",50,"text"), 
           ("email",50,"text") ]) 

    return column_title_list 
+0

嗨,看下面.. – alj 2010-05-29 14:09:43

0

嘗試用一個列表,而不是一個元組的工作。當你完成裝配時,你可以把一個列表變成一個元組。

#!/usr/bin/env python 

def getproducts(): 
    temp_list=[] 
    # usually this would come from a db 
    product_list=['focus','fiesta','mondeo','puma'] 
    for p in product_list: 
     temp_list.append((p, 30, 'text')) 
    return temp_list 

def createlist():  
    column_title_list = [ 
     ("id", 20, "integer"), 
     ("companyname", 50, "text") 
    ] 
    column_title_list += getproducts() 
    column_title_list += [ 
     ("contact", 50, "text"), 
     ("email", 50, "text"), 
    ] 

    return tuple(column_title_list) 

for item in createlist(): 
    print item 

這將導致:

# ('id', 20, 'integer') 
# ('companyname', 50, 'text') 
# ('focus', 30, 'text') 
# ('fiesta', 30, 'text') 
# ('mondeo', 30, 'text') 
# ('puma', 30, 'text') 
# ('contact', 50, 'text') 
# ('email', 50, 'text') 
2

這可能不是你要找的答案,但爲什麼浪費時間去尋找解決這個奇特的方式,當直線前進解決方案讓你繼續前進並解決程序中更有趣的部分?

def createlist(): 
    tmp = [] 
    tmp.extend([("id",20,"integer"), ("companyname",50,"text")]) 
    tmp.extend(getproducts()) 
    tmp.extend([("contact",50,"text"), ("email",50,"text")]) 
    return tuple(tmp) 
+0

感謝布賴恩。明智的話。我總是陷入困境,試圖想出一些聰明的東西。那爲什麼它需要我很久。 – alj 2010-05-29 14:11:26