Python代码输出<map object>与<filter object>异常问题求助
问题分析与解决
问题根源
在Python 3中,map()和filter()函数返回的是迭代器对象,而非直接生成列表。当你直接打印这些对象时,Python会输出它们的内存地址(如<map object at 0x00000...>),而非预期的元素列表。
解决方法1:在函数内部转为列表
修改scale和goodSales函数,将map/filter的结果用list()包裹,直接返回列表:
import sys #Multiply the value in the list based on the selected value of s def scale(l, s): return list(map(lambda x: x * s, l)) # 转换为列表返回 #Sort the value based on the last digit value def sort(l): return sorted(l, key=lambda x: x % 10) #Output number if is greater than average total def goodSales(l): return list(filter(lambda x: x > sum(l) / len(l), l)) # 转换为列表返回 seq = sys.argv[1] sca = sys.argv[2] seq = [int(x) for x in seq.split(',')] sca = int(sca) print('The scaled number is:', scale(seq, sca), 'The sorted sales numbers are:', sort(seq), 'The good sales numbers are:', goodSales(seq),)
解决方法2:在打印时转为列表
如果不想修改函数,可在print语句中对scale()和goodSales()的返回值做列表转换:
# 其他代码保持不变,仅修改print行 print('The scaled number is:', list(scale(seq, sca)), 'The sorted sales numbers are:', sort(seq), 'The good sales numbers are:', list(goodSales(seq)),)
验证结果
运行命令 python sales.py 10,20,30,40,50,60 2,会得到预期输出:
The scaled number is: [20, 40, 60, 80, 100, 120] The sorted sales numbers are: [10, 20, 30, 40, 50, 60] The good sales numbers are: [40, 50, 60]
内容的提问来源于stack exchange,提问作者theslasher
相关产品推荐
相关产品推荐

