inp = input("Input an animal and a count, or quit to quit: ")
animalList = []
while inp != 'quit':
val = inp.split(",")
animalList[val[0]] = animalList.get(val[0], 0) + int(val[1])
inp = input("Input animal and a count, or quit to quit: ")
print(animalList)
print("The total number of animal is", sum(animalList), "the average is",
1.0 * sum(animalList) / len(animalList))我希望将数据存储在元组列表中,并将重复项添加到已存储的计数中。就像这样->(猫,9),(狗,7)
并得到动物总数和平均计数。打印->
动物,数猫,9狗,7
但是我的循环似乎不能正常工作。有什么建议吗?
发布于 2018-02-02 21:24:39
要避免dict,您可以使用如下代码:
inp = input("Input an animal and a count, or quit to quit: ")
animals = []
count = []
while inp != 'quit':
val = inp.split(",")
if val[0] in animals:
count[animals.index(val[0])] += int(val[1])
else:
animals.append(val[0])
count.append(int(val[1]))
animalList = list(zip(animals, count))
print(animalList)
print("The total number of animal is", sum(count), "the average is",
1.0 * sum(count) / len(count))或者,如果您想再次使用animalList:
print("The total number of animal is", sum([i[1] for i in animalList]), "the average is",
1.0 * sum([i[1] for i in animalList]) / len(animalList))发布于 2018-02-02 21:33:58
您也可以通过给定的计数来存储它们:
inp = input("Input an animal and a count, or quit to quit: ")
animalList = []
while inp != 'quit':
animal, count = inp.split(",")[0:2]
animalList.extend([animal]*int(count)) # extend list with as much animals as given
inp = input("Input animal and a count, or quit to quit: ")
animalList.sort() # sort them together
print(animalList) # print for debug
for a in set(animalList): # print once for each animal
print("The total number of animal ", a , " is ", animalList.count(a), " the average is ", float(animalList.count(a)) / len(animalList))输入:
a,4
b,3
a,6
c,1
c,1输出:
['a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'b', 'b', 'b', 'c', 'c']
The total number of animal a is 10 the average is 0.6666666666666666
The total number of animal b is 3 the average is 0.2
The total number of animal c is 2 the average is 0.13333333333333333https://stackoverflow.com/questions/48583440
复制相似问题