0

我一直在尝试制作执行以下操作的循环或列表压缩:

然后prints"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: list index out of range”。我已经尝试了一堆“如果”和“休息”,但我无法成功。

代码中的名称等是从我的母语翻译而来的,因此最终的拼写错误可能不在代码中。

4

2 回答 2

0
# 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()]))
于 2013-09-10T19:33:37.397 回答
0
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])))
于 2013-08-07T22:10:16.193 回答