2014-12-25 4 views
1

저는 CodeAcademy에서 Python 과정을 마쳤으며 (CodeAcademy가 아닌 컴퓨터에서 코드를 실행 중입니다) 장바구니에 항목을 추가하기 위해이 코드를 작성했습니다. 장바구니는 사전입니다.Python : 장바구니에 여러 제품 및 가격 추가

class ShoppingCart(object): 

    """Creates shopping cart objects 
    for users of our fine website.""" 

    items_in_cart = {} 

    def __init__(self, customer_name): 
     self.customer_name = customer_name 

    def add_item(self, product, price): 
     """Add product to the cart.""" 
     if not product in self.items_in_cart: 
      self.items_in_cart[product] = price 
      print product + " added." 
     else: 
      print product + " is already in the cart." 

my_cart = ShoppingCart("Amy") 

my_cart.add_item("Nishiki Modulus", "$400") 

print my_cart.items_in_cart 

이 코드는 작동 반환 :

Nishiki Modulus added. 
{'Nishiki Modulus': '$400'} 

하지만 동시에 여러 항목 (및 가격)를 추가하는 방법을 알아낼 싶습니다. 나는 행운을 시험해왔다. 내가 예상대로

내가

class ShoppingCart(object): 

    items_in_cart = {} 
    def __init__(self, customer_name): 
     self.customer_name = customer_name 

    def add_item(self, product, price): 
     """Add product to the cart.""" 
     for products in product: 
      if not products in self.items_in_cart: 
       self.items_in_cart[products] = price 
       print "added." 
      else: 
       print "Product is already in the cart." 

my_cart = ShoppingCart("Amy") 

my_cart.add_item(["Nishiki Modulus", "Trek 700", "Fuji Sportif"], ["$400", "$450", "$700"]) 

print my_cart.items_in_cart 

를 실행, 키는 값 권리 만이 아니다. 이것은 반환

added. 
added. 
added. 
{'Trek 700': ['$400', '$450', '$700'], 'Fuji Sportif': ['$400', '$450', '$700'],  'Nishiki Modulus': ['$400', '$450', '$700']} 

이 난의 라인을 따라 뭔가 생각 :

for products, price in product.items(): 

을하지만 그때 내가 제대로

수있는 사람 점을 items_in_cart에 목록을 추가하는 방법을 알아낼 수 없습니다 내게 올바른 방향으로? 불명확 한 점이 있으면 알려주십시오.

+0

명확하고 의미있는 코드를 작성하십시오. 이것은 당신과 다른 사람들이 무슨 일이 일어나고 있는지 그리고 코드의 의도가 무엇인지 이해하는 데 도움이 될 것입니다. 예를 들어 '제품 내의 제품'은 무의미합니다. '제품'은 각 단일 항목이고 '제품'은 여러 항목입니다. –

+0

감사합니다 존, 나는 당신이 말하는 것을 이해합니다.나는 복수형을 놓치고 이것이 혼란 스러울 수 있습니다. 나는 더 나은 형태로 코드를 작성하려고 노력할 것이다. –

답변

0

당신은 productprice 목록을 압축하여 두 목록에서 한 번에 하나 개의 값을 줄 것이다이

for prod, money in zip(product, price): 
    if not prod in self.items_in_cart: 
     self.items_in_cart[prod] = money 
     print "added." 
    else: 
     print "Product is already in the cart." 

이 같은 제품과 가격을 zip 수 있습니다. 그래서 우리는 제품과 그에 상응하는 가격을 얻을 것입니다.

또는 당신은 당신이 간단한 인덱스 for 루프를 시도 할 수 product 목록을 반복하고,이

for index, prod in enumerate(product): 
    if not prod in self.items_in_cart: 
     self.items_in_cart[prod] = price[index] 
     print "added." 
    else: 
     print "Product is already in the cart." 
+0

감사! 필자는 아직 파이썬과 프로그래밍에 대해 잘 알고 있지만 zip 함수를 찾지는 못했습니다. –

0

처럼 인덱스와 price에서 해당 값을 얻을 수 있습니다 :

def add_item(self, product, price): 
    """Add product to the cart.""" 
    for index in range(len(product): 
     if not product[index] in self.items_in_cart: 
      self.items_in_cart[product[index]] = price[index] 
      print "added." 
     else: 
      print "Product is already in the cart." 

또는 zip :

for products, prices in zip(product, price): 
0

items_in_cart [product] 값을 price로 설정하면 문자열 목록이됩니다. 가격의 문자열 중 하나로 설정해야합니다.

여기에 고정 된 shoppingCart가 클래스는 다음과 같습니다

class ShoppingCart(object): 

    items_in_cart = {} 
    def __init__(self, customer_name): 
     self.customer_name = customer_name 

    def add_item(self, product, price): 
     """Add product to the cart.""" 
     priceIndex = 0 
     for products in product: 
      if not products in self.items_in_cart: 
       self.items_in_cart[products] = price[priceIndex] 
       print "added." 

      else: 
       print "Product is already in the cart." 

      priceIndex += 1 
0

내가 루프에서 원래 add_item를 호출하는 새로운 방법 add_items을 추가합니다. 이렇게하면 코드를보다 깔끔하고 쉽게 처리 할 수 ​​있습니다.

class ShoppingCart(object): 

    items_in_cart = {} 
    def __init__(self, customer_name): 
     self.customer_name = customer_name 

    def add_item(self, product, price): 
     """Add product to the cart.""" 
     if not product in self.items_in_cart: 
      self.items_in_cart[product] = price 
      print product + " added." 
     else: 
      print product + " is already in the cart." 

    def add_items(self, products, prices): 
     for product, price in zip(products, prices): 
      self.add_item(product, price) 

my_cart = ShoppingCart("Amy") 

my_cart.add_items(["Nishiki Modulus", "Trek 700", "Fuji Sportif"], ["$400", "$450", "$700"]) 
print my_cart.items_in_cart 
관련 문제