字符串格式化itertools输出 - 元组超出范围错误

时间:2017-08-25 17:02:20

标签: python format itertools

我正在尝试使用map和itertools将外部产品的结果输出到文件中,我很难理解为什么会产生索引错误。

import itertools
a = [1,2,3]
b = [4,5,6]
with open('job.list', 'w') as l:
    map(lambda x: l.write("{0} {1}\n".format(x)), itertools.product(a, b))

将地图更改为

map(lambda x: l.write("{0} {1}\n".format(x[0], x[1])), itertools.product(a, b))

删除了错误,但这显然是不完美的。

我猜这个错误与itertools.product有关,它返回迭代器而不是列表。但是尝试

map(lambda x: l.write("{0} {1}\n".format([d for d in x])), itertools.product(a, b))

仍会导致索引错误。

显然我的理解存在差距,但我可以帮助看看它是什么。

2 个答案:

答案 0 :(得分:0)

您的错误来自于format"{0} {1}\n".format(x)期望将两个值插入{0}{1}的事实。但是,您只提供一个 - x - 并且它不知道它应该使用该可迭代中的各个项目。相反,您可以使用splat运算符*来解包元组:

map(lambda x: l.write("{0} {1}\n".format(*x)), itertools.product(a, b))

答案 1 :(得分:0)

您可以调整参数或格式字符串以使它们匹配。前一种方法由@roganjosh发布。这是后一种选择:

"{0[0]} {0[1]}\n".format(x)
相关问题