【问题标题】:Printing out a 2-D list so that each list prints out on a new line for the output in python3?打印出一个二维列表,以便每个列表在 python3 中的输出中打印出一个新行?
【发布时间】:2022-12-18 19:48:15
【问题描述】:

*我是编程的新手,所以如果我的代码有任何可以改进的地方,请告诉我。

我想让输出每次都在新行中打印出列表,我以某种方式做到了这一点 :),但它也多次打印 [None],有人可以向我解释为什么会这样吗以及我如何能够摆脱它,无论是通过使用“\r”还是其他东西。

这是我的代码:

# 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]

【问题讨论】:

    标签: python-3.x


    【解决方案1】:

    我想我已经弄明白了。 https://www.geeksforgeeks.org/python-map-function/

    map 函数根据可迭代对象的数量运行给定的函数。在这种情况下,可迭代对象是一个包含比萨饼价格和比萨饼配料的列表。问题是这些对象作为两个单独的对象存储在某个地方,当您要求将其映射为列表时,它发现的迭代次数超过了它需要继续进行的次数。

    注意如何打印出 7 个 nones,这是它​​通过前七个项目的证据:1、奶酪、2、橄榄、2、意大利辣香肠和 2

    并按应有的方式输出,但随后继续为剩余的 7 个项目输出内容。蘑菇,3个,香肠,6个,菠萝,2.5个,辣椒。

    但它没有任何输出,因为可迭代的那些部分中没有存储任何内容,您已经用完了引用。

    这就是正在发生的事情。然而,至于解决它,我不得不说我对发生的变量类型更改数量感到有点困惑。我建议学习 Python 中的字典,因为它们是让字符串变量按可索引值排序的最佳工具,因此您可以将价格和浇头匹配到一个对象中,而不必像 map() 函数那样费劲

    【讨论】:

      猜你喜欢
      • 2015-12-21
      • 2016-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多