Issue
How can I use a for loop to print out and calculate the sum of the second character in each line (2,6,8,2,6,8)?
a = [[1, 2, 3, 4], [5, 6], [7, 8, 9], [1, 2, 2, 4], [5, 6,2], [7, 8, 9]]
s = 0
for i in range(len(a)):
for j in range(len(a[i])):
s += a[i][j]
print(s)
Solution
You could loop over the list's length and access each sublist by index:
s = 0
for i in range(len(a)):
s += a[i][1]
And of course, you could replace this with a generator expression:
s = sum(x[1] for x in a)
Answered By - Mureinik
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.