2011-01-28 49 views
-2

我是新來的Python,並且正在努力理解列表解析,所以我可以在我的代碼中使用它。編制列表理解,初學者

pricelist = {"jacket":15, "pants":10, "cap":5, "baseball":3, "gum":1} 

products_sold = [] 

while True: 
    product_name = input("what is the name of the product") 
    product = {} 
    customer_name = input("what is the name of the customer") 
    #customer is shopping 
    product[sell_price] = pricelist[product_name] 
    product["quantity"] = input("how many items were sold?") 
    #append the product to a dict 

    products_sold.append(product) 

現在我想對整個交易的字典看起來應該像這樣的:

transaction = {"customer_name":"name", 
       "sold":{"jacket":3, "pants":2}, 
       "bought":{"cap":4, "baseball":2, "gum":"10"}} 

我將如何創建一個字典,並用列表理解爲它分配鍵和值?我已經看過例子,並且我理解它們,但我無法弄清楚如何將它們應用於我的代碼。

我的意圖是將我的產品列表變成一個以不同方式包含相同信息的字典(交易)列表。

+0

產品是字典嗎? `products_sold`最終是一個列表,每個列表中有1個條目? – mikej 2011-01-28 15:47:10

回答

2

我會回答我認爲你真正的問題是你想了解列表解析。國際海事組織,你發佈的例子,試圖學習列表解析不是一個好例子。這是一個我喜歡使用的非常簡單的示例,因爲應該很容易將它與您從另一種語言中已知的內容聯繫起來。

# start with a list of numbers 
numbers = [1, 2, 3, 4, 5] 

# create an empty list to hold the new numbers 
numbers_times_two = [] 

# iterate over the list and append the new list the number times two 
for number in numbers: 
    numbers_times_two.append(number * 2) 

希望上面的代碼有意義且對您來說很熟悉。下面是使用列表解析的完全相同的東西。注意,所有相同的部件都在那裏,只是稍微移動一下。

numbers_times_two = [number * 2 for number in numbers] 

列表解析使用方括號就像一個列表,並將其從創建遍歷一個可迭代(列表類似的東西)一個新的列表,它是在這個例子中的數字。

所以,你可以看到,當你問一個關於使用列表理解來填充字典的問題時,在學習列表解析的機制的上下文中它確實沒有意義。

希望這會有所幫助。