使用列表和元组获取列表(不使用字典)

时间:2018-02-02 13:10:11

标签: python-3.x

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))

我想将数据存储在元组列表中,并将重复项添加到已存储的计数中。 像这样的东西 - > [(cat,9),(dog,7)]

获取动物总数和平均数。打印 - >

动物,伯爵 猫,9 狗,7

但我的循环似乎无法正常工作。有什么建议吗?

2 个答案:

答案 0 :(得分:2)

要避免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))

答案 1 :(得分:0)

您也可以按给定的数量存储它们:

  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.13333333333333333