即使for循环正常工作,我也无法使列表理解语句生效。我用它来创建一个包含reportlab的Table类
的表# 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)
答案 0 :(得分:8)
使用extend
代替append
:
heading.extend((s['name'],s['price'],s['note']) for s in services)
append
创建一个新元素并获取它所获得的任何内容。如果它获得一个列表,它会将此列表作为单个新元素附加。
extend
获得一个可迭代的并添加与此iterable包含的新元素一样多。
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]