python - Python .join 交互未按预期工作
问题描述
我正在编写一个有趣的脚本来提供披萨配料,所以我运行以下代码:
import random
# initializing toppings list
toppings_list = ["pepperoni", "cheese", "sausage", "peppers", "onions", "olives", "green onion", "mushroom", "anchovies", "bacon", "pancetta", "tomatoes", "garlic"]
# get a random number of toppings on this pizza
number_toppings = random.randint(0, len(toppings_list))
# get set of random toppings
for i in range(number_toppings):
pizza_string = ", ".join(random.choice(toppings_list))
# return a whole pizza with a random set of toppings
print ("Your " + str(number_toppings) + " topping pizza is : " + pizza_string)
但输出是:
Your 5 topping pizza is : g, a, r, l, i, c
和
Your 9 topping pizza is : g, a, r, l, i, c
和
Your 12 topping pizza is : o, n, i, o, n, s
我在这里遗漏了一些基本的东西,但是为什么浇头列表的每个字母都单独返回?如果我如下更改最后一行,则每个顶部都会作为列表中的一个整体返回。那么我在 .join 命令上做错了什么?
import random
# initializing toppings list
toppings_list = ["pepperoni", "cheese", "sausage", "peppers", "onions", "olives", "green onion", "mushroom", "anchovies", "bacon", "pancetta", "tomatoes", "garlic"]
# get a random number of toppings on this pizza
number_toppings = random.randint(0, len(toppings_list))
# get set of random toppings
for i in range(number_toppings):
pizza_string = ", ".join(random.choice(toppings_list))
# return a whole pizza with a random set of toppings
# print ("Your " + str(number_toppings) + " topping pizza is : " + pizza_string)
print ("Your " + str(number_toppings) + " topping pizza is : " + random.choice(toppings_list))
结果是:
Your 7 topping pizza is : pancetta
和
Your 6 topping pizza is : anchovies
和
Your 5 topping pizza is : green onion
解决方案
干得好:
import random
# initializing toppings list
toppings_list = ["pepperoni", "cheese", "sausage", "peppers", "onions", "olives", "green onion", "mushroom", "anchovies", "bacon", "pancetta", "tomatoes", "garlic"]
# get a random number of toppings on this pizza
number_toppings = random.randint(0, len(toppings_list) - 1)
# get set of random toppings
pizza_string = ", ".join(random.sample(toppings_list, k=number_toppings))
# return a whole pizza with a random set of toppings
print ("Your " + str(number_toppings) + " topping pizza is : " + pizza_string)
推荐阅读
- javascript - 反应本机获取数据
- css - 在浏览器的 100% 和 80% 缩放级别上,将弹出窗口保持在同一位置
- types - INCLUDE 中的声明在主程序中不被识别
- python - Python -V 在 Windows 10 上不起作用或返回任何错误
- angular - 忽略未捕获的错误错误:服务器提前终止,状态为 3221225477
- c# - 在 Xamarin 的 xmlns 中找不到类型 Ellipse
- apache-flink - 了解 Flink 中 Operator 之间的数据传输(Batch)
- powerbi - 用零替换空白以获得一些意想不到的额外行
- airflow - Pod 启动失败:Pod 启动时间过长,无法运行 KubernetesPodOperator 密码
- python - 在 python 中运行多处理时共享内存全局列表