What is the different between these two list comprehension calculations?

时间:2018-02-03 11:05:55

标签: python python-3.x

I've been running my own statistical analyses, but I'm curious as to why there are different outputs for the following two list comprehensions. I am using Jupyter Notebook on Ubuntu LTS 16.04:

Input:

example = [[15, 16, 17],
           [18, 19, 20]]

list1 = [item[0] + item[1] + item[2] for item in example]

for item in example:

    list2 = [item[0] + item[1] + item[2]]

list1, list2

Output: ([48, 57], [57])

Clearly the second function is printing the sum of the second row, but why not the first?

2 个答案:

答案 0 :(得分:0)

The second example is not a list comprehension, the final list has only one item as you're overwriting list2 variable with every loop execution.

答案 1 :(得分:0)

To get the same output, the second loop should be corrected to this:

list2 = []
for item in example:
    list2.append(item[0] + item[1] + item[2])

Otherwise you overwrite what you had assigned to list2 in the previous iteration of the loop, only getting the result of the last iteration.

相关问题