我的任务是创建一个for循环来添加偶数并从数字列表中减去不均匀的数字。这样的事情:list = [(6,(+8),(-95),(+2),(+12),(+152),(+4),(+78),(-621),(-45))]
我不确定从哪里开始,但我到目前为止:
list = [6,8,95,2,12,152,4,78,621,45]
sum = 0
for x in list:
if list (0 % 2) == 0:
sum = sum + list[x]
elif list (0 % 2) != 0:
sum = sum - list[x]
return sum
虽然不确定如何遍历列表......
答案 0 :(得分:2)
不要将list
用作变量名称,因为它会隐藏list
数据类型!
lst = [6, 8, 95, 2, 12, 152, 4, 78, 621, 45]
total = 0
for x in lst:
if x % 2: # odd
total -= x
else: # even
total += x
编辑:只是为了好玩,您也可以尝试
total = sum(x * (1 - (x % 2 * 2)) for x in lst)
确定其工作原理的奖励点; - )
答案 1 :(得分:1)
你可以使用conditional expression和for循环添加偶数并将奇数减去运行总数/ sm:
lst = [6,8,95,2,12,152,4,78,621,45]
sm = 0
for ele in lst:
sm = sm + ele if not ele % 2 else sm - ele
对于偶数, if not ele % 2
将为True,因为0
是一个假值。
您还可以查看least significant bit, if ele & 1
,如果True表示数字是奇数,或if ele & 0
找到偶数数字:
sm = 0
for ele in lst:
sm = sm - ele if ele & 1 else sm + ele
print(sm)
可以将所有内容都放在generator expression中:
print(sum(-ele if ele & 1 else ele for ele in lst))
sum
是内置函数list
,因此请尽量避免将其用作变量名。
只是为了感兴趣一些时间:
In [8]: timeit sum(-x if x % 2 else x for x in lst)
1000000 loops, best of 3: 1.44 µs per loop
In [9]: %%timeit
sm = 0
for ele in lst:
sm = sm + ele if not ele % 2 else sm - ele
...:
1000000 loops, best of 3: 1.12 µs per loop
In [11]: timeit sum(-ele if ele & 1 else ele for ele in lst)
1000000 loops, best of 3: 1.27 µs per loop
In [13]: %%timeit
sm = 0
for ele in lst:
sm = sm + ele if not ele % 2 else sm - ele
....:
1000000 loops, best of 3: 1.11 µs per loop
In [14]: %%timeit
sm = 0
for ele in lst:
sm = sm - ele if ele & 1 else sm + ele
....:
1000000 loops, best of 3: 875 ns per loop
In [15]: %%timeit
....: total = 0
....: for x in lst:
....: if x % 2: # odd
....: total -= x
....: else: # even
....: total += x
1000000 loops, best of 3: 1.02 µs per loop
In [16]: timeit sum(x * (1 - (x % 2 * 2)) for x in lst)
100000 loops, best of 3: 2.2 µs per loop
答案 2 :(得分:0)
使用+=
和-=
添加/减去总和。
num_list = [6,8,95,2,12,152,4,78,621,45]
sum = 0
for x in num_list:
if x % 2 == 0:
sum += x
else:
sum -= x
答案 3 :(得分:0)
你可以在一行中实现这一点,作为列表理解:
print sum([j * [1, -1][j % 2] for j in data])