[英]Python: using loops with lists
Say I have a list:说我有一个清单:
list1=[[1,2,3,4],[5,6,7],[8,9,0,11]]
list1
.同样,我想找到所有子列表的总和,基本上是list1
的总和。How do I write the code for that?我如何为此编写代码?
Here's the code I tried:这是我试过的代码:
a=[[1,2,3], [1,5,4], [2,4,5]]
i = 0
sum = 0
b=a[1]
while ( i < len(b) ) :
sum = sum + b[i]
i = i + 1
print ( sum )
a=[[1,2,3], [1,5,4], [2,4,5]]
i = 0
sum = 0
c=a[2]
while ( i < len(c) ) :
sum = sum + c[i]
i = i + 1
print ( sum )
a=[[1,2,3], [1,5,4], [2,4,5]]
i = 0
sum = 0
d=a[0]
while ( i < len(d) ) :
sum = sum + d[i]
i = i + 1
print ( sum )
The output:输出:
10
11
6
I want to find the sum of the given numbers.我想找到给定数字的总和。 How do I modify the code?如何修改代码? I'm using python3.我正在使用python3。 Loops to be used: while
and for
.要使用的循环: while
和for
。
One problem is that you are declaring a variable called sum that is overriding a Python built-it function by the same name.一个问题是您声明了一个名为sum的变量,该变量覆盖了同名的 Python 内置函数。 Once you do that the sum() function won't be available in that instance of Python.一旦你这样做了sum()函数在那个 Python 实例中将不可用。
Keep in mind that lists are iterable.请记住,列表是可迭代的。 So to get each sublist:所以要获取每个子列表:
list1=[[1,2,3,4],[5,6,7],[8,9,0,11]]
for sublist in list1:
print(sublist)
[1, 2, 3, 4]
[5, 6, 7]
[8, 9, 0, 11]
You could print out each element individually:您可以单独打印出每个元素:
for sublist in list1:
print(*sublist)
1 2 3 4
5 6 7
8 9 0 11
Or print a newline after each element:或者在每个元素后打印一个换行符:
for sublist in list1:
print(*sublist, sep='\n')
1
2
3
4
5
6
7
8
9
0
11
Since a list is iterable it can be summed using the built-in function sum() .由于列表是可迭代的,因此可以使用内置函数sum()对其进行求和。 Which one is easier to read?哪一个更容易阅读?
my_sum = sum(sublist)
OR或者
my_sum = 0
for number in sublist:
my_sum += number
You could keep track of each sublists' sum in a variable declared outside of the loop.您可以在循环外声明的变量中跟踪每个子列表的总和。
sums = 0
for sublist in list1:
sums += sum(sublist)
print(sums)
56
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.