2013-03-01 91 views
2

即使for循環正常工作,我也無法讓列表理解語句正常工作。我用它來創建一個表ReportLab的的表類正常for循環工作正常時,列表理解不起作用

# Service Table 
heading = [('Service', 'Price', 'Note')] 

# This doesn't work as in there is no row in the output 
heading.append([(s['name'],s['price'],s['note']) for s in services]) 
table = Table(heading) 

# This displays the table correctly 
for s in services: 
    heading.append((s['name'], s['price'], s['note'])) 
table = Table(heading) 

回答

8

使用extend而不是append

heading.extend((s['name'],s['price'],s['note']) for s in services) 

append創建新的元素,並採取一切可能得到。如果它獲得一個列表,它會將這個列表附加爲一個新的元素。

extend獲得一個迭代並添加儘可能多的這個迭代包含的新元素。

a = [1, 2, 3] 
a.append([4,5]) 
# a == [1, 2, 3, [4, 5]] 

a = [1, 2, 3] 
a.extend([4,5]) 
# a == [1, 2, 3, 4, 5] 
+0

謝謝。這是現貨。 – 2013-03-01 09:14:18