簡體   English   中英

python 3.x中的列表理解/列表創建循環

[英]List comprehension/list creating loop in python 3.x

我一直在試圖做一個循環或列表強制,它可以執行以下操作:

打印"Please give me the number of bread sold at ", self.bakeryname[k], ":"然后提示用戶輸入在給定面包店出售的"Please give me the number of bread sold at ", self.bakeryname[k], ":"數量,並將其存儲在列表中

"Please give me the number of [breadtype] sold at:"
"The hungry baron": [here you enter a number]
"The flying bulgarian": [here you enter another number]

它要存儲在一個整數列表中,該整數列表從第一個提示值開始,到最后一個-||-結尾。

面包店的數量可能是無限的,只有3種不同類型的面包。

我將自己挖入了這個功能的孔中:

def soldbread(self):
    amount = ((len(self.bakeryname))*3)
    k = 0
    j = 0
    h = 0
    i = 0
    while j < (len(self.breadtype)):
            print("Please give me the number of",self.breadtype[k], "sold at:")
            while i < amount:
                self.breadsold.append(i)
                self.breadsold[i] = int(input(self.bakeryname[h]))
                j += 1
                h += 1
                i += 1
                if k == 3:
                    break
                else:
                    while j >= len(self.bakeryname):
                        k += 1
                        print("Please give me the number of",self.breadtype[k], "soldat:")
                        j = 0
                        h = 0

該函數將轉到第15種面包(self.bakeryname中目前有5個面包店,<現在,因此該數字至少是准確的),然后它將抱怨“ IndexError:列表索引超出范圍”。 我已經嘗試了很多“如果”和“休息”的情況,但是我無法實現。

代碼中的名稱等是從我的母語翻譯過來的,因此最終的錯別字很可能不在代碼中。

bakeries = ['a','b','c']
breadtypes = ['flat','rye','white']

results = []
for i in bakeries:
   print('How many of each type of bread for {0}:'.format(i))
   number_of_types = []
   for bread in breadtypes:
       number_of_types.append(input('{0}:'.format(bread)))
   results.append(number_of_types)

for k,v in enumerate(bakeries):
   print('Here are the different types of breads for {0}'.format(v))
   print(''.join('{0}:{1}'.format(a,b) for a,b in zip(breadtypes, results[k])))
# Your data
bakeries = ['a','b','c']
breadtypes = ['flat','rye','white']
# Output data
results = {}

for bakery in bakeries:
    # A line for each bakery
    print('How many of each type of bread for %s: ' % bakery)

    # The python3 dict comprehension and a generator
    results[bakery] = {
        breadtype: breadtypevalue for breadtype, breadtypevalue
        in ((bt, input('%s: ' % bt)) for bt in breadtypes)
    }

# Wanna print that?
for bakery in results:
    print('Here are the different types of breads for %s:' % bakery)
    print(', '.join(['%s: %s' % (breadtype, number) for breadtype, number in results[bakery].items()]))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM