首页 > 解决方案 > 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

标签: python

解决方案


干得好:

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)

推荐阅读