首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用列表和元组获取列表(不使用字典)

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

Stack Overflow用户
提问于 2018-02-02 21:10:11
回答 2查看 50关注 0票数 1
代码语言:javascript
复制
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

但是我的循环似乎不能正常工作。有什么建议吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-02-02 21:24:39

要避免dict,您可以使用如下代码:

代码语言:javascript
复制
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

代码语言:javascript
复制
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))
票数 2
EN

Stack Overflow用户

发布于 2018-02-02 21:33:58

您也可以通过给定的计数来存储它们:

代码语言:javascript
复制
  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))

输入:

代码语言:javascript
复制
a,4
b,3
a,6
c,1
c,1

输出:

代码语言:javascript
复制
['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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48583440

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档