迭代浮点宽度列表:TypeError: sequence expected, generator found



我正在尝试迭代一个浮动宽度变化的列表。

[10.5, 15.5, 3.7]  <- Randomly generated 

我正在使用这个浮点数列表来生成我试图打印的字符串列表之间的空格。我通过

print ''.join('%*s' %i for i in zip(WIDTHS, LIST_OF_STRINGS))

我得到错误

TypeError: sequence expected, generator found

谁能解释为什么我得到这个错误?

编辑:Python Version 2.4

您实际上应该得到错误消息

TypeError: * wants int

先将浮点数转换为整型:

widths = map(int, widths)

的例子:

>>> widths = [10.5, 15.5, 3.7]
>>> s = ["a", "b", "c"]
>>> widths = map(int, widths)
>>> ''.join('%*s' %i for i in zip(widths, s))
'         a              b  c'

我以几种方式修改了您的代码。现在它在这里工作(Python 2.7):

strings = ['a','b','c']
widths1 = [10, 15, 3]
widths2 = [5, 5, 7]
''.join('%*.*s' %i for i in zip(widths1, widths2, strings))

搜索结果

'         a              b  c'

格式字符串中的宽度值不是浮点数,而是两个整数,由.分隔。

相关内容

最新更新