You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python3中二维列表换行打印出现[None]的问题解决

二维列表换行打印后末尾出现None列表的问题解决

问题描述

作为编程新手,我想实现二维列表的换行打印,目前已经能打出换行效果,但输出末尾会出现一个由多个None组成的列表。以下是我的代码和当前输出:

原代码

# All Toppings
toppings = ["cheese", "olives", "pepperoni", "mushrooms", "sausage", "pineapple", "anchovies"]

# The Prices
prices = ["$2", "$6", "$1", "$3", "$2", "$7", "$2"]
prices.sort()

# Number of Toppings
num_pizzas = len(toppings)

# Combing Pizza Toppings and Prices
pizza_and_prices = list(map(list,zip(prices,toppings)))

#After the Guy Bought the Last Anchovies Slice
pizza_and_prices.pop()
pizza_and_prices.append(["$2.5", "peppers"])

#ACTUAL MENU
print("***TOOZIE'S PIZZARIA***")
print("We sell " + str(num_pizzas) + " different kinds of Pizza!")
print(list(map(print, pizza_and_prices)))

当前输出

***TOOZIE'S PIZZARIA***
We sell 7 different kinds of Pizza!
['$1', 'cheese']
['$2', 'olives']
['$2', 'pepperoni']
['$2', 'mushrooms']
['$3', 'sausage']
['$6', 'pineapple']
['$2.5', 'peppers']
[None, None, None, None, None, None, None]

问题原因

问题出在最后一行代码print(list(map(print, pizza_and_prices))):

  • map(print, pizza_and_prices)会遍历pizza_and_prices的每个元素,对每个元素调用print()函数,这一步已经完成了换行打印的操作;
  • 但print()函数本身没有返回值,默认返回None,所以map会把每个print()调用后的None收集成一个迭代器;
  • 接着list()把这个迭代器转换成包含多个None的列表,最后外层的print()又把这个列表打印出来,就出现了末尾的[None, None, ...]。

解决方法

只需要去掉外层的print(list(...)),换成直接遍历打印每个元素即可,有两种常用方式:

方法一:for循环遍历(最直观)

把最后一行代码替换成:

for item in pizza_and_prices:
    print(item)

方法二:遍历map对象(不生成列表)

如果想保留map的用法,直接遍历map对象即可,不需要转成列表再打印:

for _ in map(print, pizza_and_prices):
    pass

修改后的完整代码示例

# All Toppings
toppings = ["cheese", "olives", "pepperoni", "mushrooms", "sausage", "pineapple", "anchovies"]

# The Prices
prices = ["$2", "$6", "$1", "$3", "$2", "$7", "$2"]
prices.sort()

# Number of Toppings
num_pizzas = len(toppings)

# Combing Pizza Toppings and Prices
pizza_and_prices = list(map(list,zip(prices,toppings)))

#After the Guy Bought the Last Anchovies Slice
pizza_and_prices.pop()
pizza_and_prices.append(["$2.5", "peppers"])

#ACTUAL MENU
print("***TOOZIE'S PIZZARIA***")
print("We sell " + str(num_pizzas) + " different kinds of Pizza!")
# 替换成for循环打印
for item in pizza_and_prices:
    print(item)

修改后输出

***TOOZIE'S PIZZARIA***
We sell 7 different kinds of Pizza!
['$1', 'cheese']
['$2', 'olives']
['$2', 'pepperoni']
['$2', 'mushrooms']
['$3', 'sausage']
['$6', 'pineapple']
['$2.5', 'peppers']

内容的提问来源于stack exchange,提问作者Toozie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 02:20:26