2016-02-10 71 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]