简体   繁体   English

增加列表的所有元素,除了 Python 中的第一个元素

[英]Increase all elements of a list except the first one in Python

I have a list T1 .我有一个列表T1 I want to increase all elements of T1 by 1 except the first element.我想将T1的所有元素都增加1 ,但第一个元素除外。 How do I do so?我该怎么做?

T1=[0,1,2,3,4,5,6,7]
T2=[i+1 for i in T1]

The current output is当前的 output 是

T2= [1, 2, 3, 4, 5, 6, 7, 8]

The expected output is预期的 output 是

T2= [0, 2, 3, 4, 5, 6, 7, 8]

Use slicing!使用切片!

T1 = [0,1,2,3,4,5,6,7]
T2 = [T1[0]] + [i+1 for i in T1[1:]]

Or, with enumerate :或者,使用enumerate

T1 = [0,1,2,3,4,5,6,7]
T2 = [x+(i>0) for i, x in enumerate(T1)]

Output: Output:

[0, 2, 3, 4, 5, 6, 7, 8]

You could separate the first element from the rest and increment the rest by 1 -您可以将第一个元素与 rest 分开,并将 rest 增加 1 -

first, *rest = t1
t2 = [first] + [(i + 1) for i in rest]

Or you could enumerate your list and use the index -或者您可以enumerate您的列表并使用索引 -

t2 = [(val + 1) if idx > 0 else val for (idx, val) in enumerate(t1)]

The correct answer would be to slice the T1 list in two, the part that you don't want to modify and the part that you do.正确的答案是将 T1 列表一分为二,您不想修改的部分和您要做的部分。 Just combine them afterwards:之后将它们组合起来:

T1=[0,1,2,3,4,5,6,7]
T2= T1[0:1] + [i+1 for i in T1[1:]]

There are several methods, 2 of them有几种方法,其中2种

T2 = [T1[0]] + [ j+1 for j in T1[1:]]

a longer but funnier one更长但更有趣的

T2 = [x+y for x,y in zip(T1, [0] + [1]*(len(T1)-1))]

or just a for loop with index, so you can decide which index to operate in或者只是一个带索引的 for 循环,因此您可以决定在哪个索引中操作

T2 = list()
for i,el in enumerate(T1):
    if i == 0:
        T2.append(el)
    else:
        T2.append(el+1)

Have fun玩得开心

I've tried this:我试过这个:

given:给定:

t1 = [0, 1, 2, 3, 4]

the t2 list may be calculated as following: t2列表可以计算如下:

t2 = t1[0:1] + [v + 1 for i, v in enumerate(t1) if i != 0]

The first part of the list concatenation is a list: in fact if you try t1[0] you get a TypeError due to the fact that is impossible to concatenate int with list .列表连接的第一部分是一个列表:事实上,如果你尝试t1[0] ,你会得到一个TypeError ,因为不可能将intlist连接起来。

I would do it like this:我会这样做:

for i in range(1,len(T1)):   
  T1[i]=T1[i]+1

This would not create a new list, but would change the values in the current list这不会创建新列表,但会更改当前列表中的值

Relatively simple answer where you use if else condition.在 if else 条件下使用的相对简单的答案。

T1=[0,1,2,3,4,5,6,7]
T2 = [x+1 if i>0 else x for i, x in enumerate(T1)]
# Output:
[0, 2, 3, 4, 5, 6, 7, 8]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM