如何在if和else语句中定义for循环的结果(在python中)?

时间:2017-10-22 22:15:09

标签: python python-3.x for-loop

我的代码可能看起来很混乱,所以我会一步一步走。这就是我所做的(有效):

我有6个列表。我的代码询问用户用户购物车中有多少商品。它需要该数字并打印从列表中选择的随机项目数(例如,如果用户为4输入items in cart,则可能会生成此随机购物车项目列表:['pineapple', 'iPhone case', 'toolbox', 'olives'])。

我的问题: 如何定义随机项目列表,如果打印'pineapple',它会在账单上加1?

items_1 =[ "soap","ketchup","pineapple","crisp","twix"]
items_2  = ["olives","mouse pad","shampoo","coke","ruler","pen"]
items_3 =  ["honey","mirror","chocolate bar","fanta"]
items_4 = ["candle","doughnuts","pencil","dr pepper","broccoli","cabbage"]
items_5 = ["book","butter","jam","umbrella","toolbox","knife"]
items_6 = [ "tissue","iphone case","jewels","sprite"]
list_of_lists = [items_1, items_2, items_3, items_4, items_5, items_6]
item_cart=int(input("how many items in the cart"))
scan10=(random.choice(random.choice(list_of_lists)))

for scan in range(item_cart):
     scan1=print(random.choice(random.choice(list_of_lists)))

#BillCreating
print("here are your items")
bill=0

if "soap" in scan1: 
   bill+1
if "ketchup" in scan1: 
   bill+1
if "pineapple" in scan1: 
   bill+1
if "crisp" in scan1: 
   bill+1
if "twix" in scan1: 
   bill+1



print("total:",(bill))

3 个答案:

答案 0 :(得分:1)

使用+=

if "pineapple" in scan1: 
    bill += 1

IIUC,您希望从6个项目列表中的任何一个中抽取随机item_cart项目,考虑首先展平list_of_lists,然后对所有可结算项目进行求和,从而收紧代码。

在这种方法中,您不必担心按顺序递增bill计数:

import numpy as np

item_list = [item for i_list in list_of_lists for item in i_list]
item_cart = int(input("how many items in the cart"))
scan1 = np.random.choice(item_list, size=item_cart)
billable_items = ["soap", "ketchup", "pineapple", "crisp", "twix"]

bill = sum([1 for b_item in billable_items if b_item in scan1])

print(f"here are your items: {scan1}")
print(f"total: {bill}")

如果你可以使用Pandas,这会变得更加紧凑:

import pandas as pd

bill = pd.Series(billable_items).isin(scan1).sum()

答案 1 :(得分:1)

bill+1bill1加在一起 ​​- 然后返回结果。

我希望您希望帐单增加1,在这种情况下,您需要实际保存结果

bill = bill + 1

Python(以及许多其他语言)都有这样做的简写。

bill += 1

答案 2 :(得分:0)

bill=0

for i in range(item_cart):
    scan1=random.choice(random.choice(list_of_lists))
    if scan1 in ["twix", "pineapple",....]:
        bill+=1

print("here are your items")
print("total: {}".format(bill))