将打印的答案转换为列表

时间:2014-11-07 14:53:10

标签: python list printing sum range

我的目标是让列表(11)中可被2整除的所有值在列表中可用,以便找到总和。这是我目前的代码:

y = list(range(11))
for x in list(range(11)):
    if x % 2 == 0:
        print(x)
    else:
        print(0)

我的输出如下:

0
0
2
0
4
0
6
0
8
0
10

3 个答案:

答案 0 :(得分:1)

声明一个空的列表变量,并通过append函数将这些项追加到声明的列表中。

L = []
y = list(range(11))
for x in list(range(11)):
    if x % 2 == 0:
        L.append(x)
    else:
        L.append(0)
print(L)

输出:

[0, 0, 2, 0, 4, 0, 6, 0, 8, 0, 10]

答案 1 :(得分:0)

a = []
y = list(range(11))
for x in list(range(11)):
    if x % 2 == 0:
        a.append(x)
    else:
        print(0)

print (a, sum(a))

或者只是这样做: -

l = [x for x in range(11) if x%2==0]
print (l, sum(l))

答案 2 :(得分:0)

代码:

results = []
y = list(range(11))
for x in y:
    if not x % 2:
        results.append(x)

print 'Numbers divisible by 2: {}'.format(results)
print 'Sum of results: {}'.format(sum(results))

输出:

Numbers divisible by 2: [0, 2, 4, 6, 8, 10]
Sum of results: 30