将每秒的数字乘以列表

时间:2016-02-10 14:12:14

标签: python

我需要能够将列表中的每秒数乘以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]

之前输入相同的列表

有没有办法完成我想要完成的任务?

6 个答案:

答案 0 :(得分:4)

你几乎就在那里,你只需要从第二个(1索引)元素开始:

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

也就是说,由于您似乎正在实施Lunh checksum,因此您只需要这些数字的总和,而无需更新原始数据,例如在this example中完成。

答案 1 :(得分: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]

答案 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)

答案 3 :(得分:0)

另一种使用枚举的解决方案:

SELECT patfile.Chart_Number
    ,patfile.employer AS e_name
FROM patfile;

IF (
        patfile.employer = ''
        ,(
            SELECT addfile.NAME AS e_name
            FROM addfile
            WHERE patfile.employer = addfile.code
            )
        ,''
        ) ELSE patfile.employer AS e_name endif

其中 i l p 元素。

答案 4 :(得分: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))]

答案 5 :(得分:0)

>>> l = [1,2,3,4]
>>> 
>>> list(map(lambda x: x*2 if l.index(x)%2 else x, l))
[1, 4, 3, 8]