2016-02-10 70 views
3

我需要能够乘以2列表中的每秒数每秒数这么说:乘以一个列表

List = [1,2,3,4] 

我想这回,我已经尝试过了[1,4,3,8]但所有的方法如

credit_card = [int(x) for x in input().split()] 

credit_card[::2] = [x*2 for x in credit_card[::2]] 

print(credit_card) 

如果我输入从它返回[2,2,6,4]

有没有办法来完成我试图完成之前相同的列表?

+0

的可能的复制[?我如何通过三三两两一个Python列表循环(http://stackoverflow.com/questions/2990121 /如何通过一个循环的python-list-by-twos) –

+1

只是一个方便的提示为您:避免使用内置的名称,如“list”,“字典” 'id'等等。(这里你使用了大'L',所以它不是这样的问题,而是一个变量'should_look_like_this'和'ClassesAreWrittenLikeThis'。使得代码更具可读性,并且可以让你头痛不已 –

回答

4

你就要成功了,你只需要在第二(1索引)元素开始:

credit_card[1::2] = [x*2 for x in credit_card[1::2]] 

这就是说,因为你似乎要实施Lunh checksum,你只需要这些的总和数字而不必更新原始数据,如this example中所做的那样。

+1

只是OP的简短解释:一般语法是'credit_card [start:stop:step]'。 '[2]'意思是“从步骤2开始采取所有元素并且'[2 :: 2]'将意味着”从第三元素开始,到结束,以2的步骤 –

0
credit_card = input().split() 
for x in len(credit_card) 
    if x % 2 != 0 
     credit_card[x] = credit_card[x] * 2 

print (credit_card) 
1
lst = [1,2,3,4] 

new_lst = [2*n if i%2 else n for i,n in enumerate(lst)]  # => [1, 4, 3, 8] 
+0

我想如果你使用'1 * x = x'而不是'0 = False',你可以最小化:-) –

+0

我不明白你的评论与我的回答有什么关系? –

+0

使用'(i%2 + 1)* n' ... –

0

使用列举的另一个解决方案:

[i* 2 if p % 2 else i for p, i in enumerate(l)] 

其中p个元件。

+0

好的答案。只要将'item'改成'i'(现在不行):) –

+0

@spoor,@Nander Speerstra:'%'运算符的目的是什么? –

+0

@Jon。基本上通过检查除2的余数是0(偶数)还是不是(奇数)来检查位置是偶数还是奇数。 – sopor

0
for i,_ in enumerate(credit_card): 
    if i%2: 
     credit_card[i] *= 2 

,或者如果你想成为幻想:

credit_card=[credit_card[i]*(2**(i%2)) for i in range(len(credit_card))] 
0
>>> l = [1,2,3,4] 
>>> 
>>> list(map(lambda x: x*2 if l.index(x)%2 else x, l)) 
[1, 4, 3, 8]