报错TypeError: sequence item 0: expected str instance, int found,如何修复矩阵显示代码?
问题分析与解决
错误原因
str.join()方法仅能拼接字符串类型的元素,你的代码中二维列表里的元素是整数(int),直接传入join()会触发类型不匹配错误:TypeError: sequence item 0: expected str instance, int found。
修改方案
将每个整数元素转换为字符串后再进行拼接,修改内层列表推导式即可:
matrix1=[[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]] # 把整数元素转为字符串类型 m2="\n".join(["\t".join([str(ritem) for ritem in item]) for item in matrix1]) print(m2)
运行结果
执行修改后的代码会输出格式化的矩阵:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
内容的提问来源于stack exchange,提问作者mohammad saeed heidari
相关产品推荐
相关产品推荐

