Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Reduce在for循环正常工作时给出错误_Python_Loops_Functional Programming_Python Unicode - Fatal编程技术网

Python Reduce在for循环正常工作时给出错误

Python Reduce在for循环正常工作时给出错误,python,loops,functional-programming,python-unicode,Python,Loops,Functional Programming,Python Unicode,我有一个包含lxml.etree.\u ElementStringResult和lxml.etree.\u elementUnicodesult的列表内容 for x in contents: final_content += (x.encode('utf-8')) + '\n' 及 第一个代码运行正常,而第二个代码引发unicode解码错误 in(a,x) ---->1最终内容=减少(λa,x:a+x.encode('utf-8')+'\n',内容) UnicodeDecod

我有一个包含lxml.etree.\u ElementStringResult和lxml.etree.\u elementUnicodesult的列表内容

for x in contents:
        final_content += (x.encode('utf-8')) + '\n'

第一个代码运行正常,而第二个代码引发unicode解码错误

in(a,x)
---->1最终内容=减少(λa,x:a+x.encode('utf-8')+'\n',内容)
UnicodeDecodeError:“ascii”编解码器无法解码位置中的字节0xc3
37:序号不在范围内(128)
编辑:

reduce失败,因为第一个元素未编码

当我把代码改成

final_content = contents[0]
for x in range(1,len(contents)):
     final_content += contents[x].encode('utf-8')

它会引发与上面的reduce块相同的错误。

该错误是因为您的
\n
未进行utf-8编码。只需将设置为unicode字符串即可解决此问题:

final_content = reduce(lambda a, x: a + x.encode('utf-8') + u'\n', contents)
很抱歉“答案所有者”未经您的许可在此处编辑您的问题,但问题已关闭,我无法发布正确答案。可以自由删除此内容:

Op,您假设两个代码是相同的行为,但事实并非如此!因为在第一次映射迭代中,您将连接第一个和第二个元素,而不使用
\n
。您正在对第二个元素进行编码,但没有对第一个元素进行编码。从经典的
for
循环到
reduce
方法的正确翻译是:

final_content = reduce(lambda a, x: 
                           a+x.encode('utf-8') + u'\n', 
                       contents, 
                       u'\n')    # <----- initializer

这就是引起错误的原因

题外话:
final\u content=u'\n.join([x.encode('utf-8')表示内容中的x])
@bhargav这个问题是关于reduce和not encodeing的问题。@danihp这个评论是针对以重复形式结束问题的mods的。好吧,伙计,我把我的答案贴在@hjpotter92答案里面了。我希望他不要难过。@danihp是的,谢谢。我找到了答案,并将代码替换为
reduce(lambda,x:a+x.encode('utf-8')+'\n',contents,contents[0]。encode('utf-8'))
应该在找到答案后对问题进行编辑。它仍然会引发相同的错误。在^comment之后更新。
final_content = reduce(lambda a, x: 
                           a+x.encode('utf-8') + u'\n', 
                       contents, 
                       u'\n')    # <----- initializer
contents[0] + contents[1].encode('utf-8')