Python 3.x 如何在列表中添加数字

Python 3.x 如何在列表中添加数字,python-3.x,Python 3.x,所以在这个列表中有15罐食物。如何创建一个函数来计算并返回列表中的罐头总量。创建一个字典,然后对字典中的值求和: the_list={‘西红柿丁’:3,‘橄榄’:2,‘西红柿汤’:3,‘金枪鱼’:7} 求和(the_list.values())挑出数字,然后将它们相加 the_list = ['diced tomatoes', 3, 'olives', 2, 'tomato soup', 3, 'tuna', 7] def count_cans(): print(len(the_list))

所以在这个列表中有15罐食物。如何创建一个函数来计算并返回列表中的罐头总量。

创建一个字典,然后对字典中的值求和:

the_list={‘西红柿丁’:3,‘橄榄’:2,‘西红柿汤’:3,‘金枪鱼’:7}

求和(the_list.values())

挑出数字,然后将它们相加

the_list = ['diced tomatoes', 3, 'olives', 2, 'tomato soup', 3, 'tuna', 7]
def count_cans():
 print(len(the_list))

给你

the_list = ['diced tomatoes', 3, 'olives', 2, 'tomato soup', 3, 'tuna', 7]
def count_cans (list) :
    sum = 0
    for element in list :
        if type (element) == int :
            sum += element
    return sum

print (count_cans (the_list))

使用O(n)性能,浏览列表一次。

您好,欢迎来到StackOverFlow!作为一般提示,如果你像维克多·威尔逊所说的那样补充你迄今为止所做的事情,那么回答你的问题对我们来说会更有帮助,但尽管如此,我们会尽力提供帮助

考虑一下您可能需要“递增”一个“计数器”变量(这里有主要提示!)。因为您使用的是列表,所以您知道它是一个iterable,因此您可以使用迭代过程,如
for loops/while loops
range()
函数来帮助您

一旦找到“罐数”(提示:type
int
),就可以使用计数器变量(提示:此处为加法)增加罐数

在学习调试自己的代码时,了解正在使用的数据类型以及可用于这些类型的内置方法非常有帮助


而且。。。当我完成我的帖子时,@bashbelam似乎已经用完整的程序回答了你;)。希望这有帮助

如果只想在列表中添加数字,可以从该列表中提取数字,然后对该子列表进行求和。这意味着

total_cans = 0
for food in the_list:
    if (isinstance(food,int)): total_cans += food

print(total_cans) 
然而,如果你告诉我们你的实际问题陈述,我觉得我们可以更有效地解决这个问题。您应该更可能使用不同的数据结构。如果您知道列表中的项目(调味品)是唯一的,请使用哈希映射/字典,或者可以使用tuple/namedtuple为您的输入数据提供结构-项目名称:项目计数。然后你可以使用更有效的技术来提取你想要的数据


我觉得这是一个家庭作业问题,我不太确定这样做的政策。尽管如此,我还是建议大家把注意力集中在这里的答案所提供的想法上,自己动手,而不是复制粘贴(伪)解决方案。

是的,您可以使用带循环的范围函数来计算数字。范围函数返回数字序列并接受3个参数 语法 范围(启动、停止、步进)。 开始和步骤是可选的

要了解范围函数,请访问

其工作原理如下:

  • 使用对列表的理解创建一个新列表
  • 从1开始,每隔一个值迭代一次
  • 然后将其传递给
    sum()
    函数

你能告诉我们你试过什么吗?
sum(列表[1::2])
也许你的意思是
count+=列表[i]
无论如何,有更简单的方法可以做到这一点。您可以迭代跳过一个列表并通过
sum(列表[1::2])
def get_number(whatever):
    try:
        return float(whatever)
    except ValueError:
        return 0


your_list = ['diced tomatoes', 3, 'olives', 2, 'tomato soup', 3, 'tuna', 7]
total = sum([get_number(i) for i in your_list])
the_list = ['diced tomatoes', 3, 'olives', 2, 'tomato soup', 3, 'tuna', 7]
def count_cans():
    count=0
    for i in range(1,len(the_list)+1,2):
        count+=int(the_list[i])
return count
the_list = ['diced tomatoes', 3, 'olives', 2, 'tomato soup', 3, 'tuna', 7]
sum([the_list[i] for i in range(1,len(the_list),2)])