简体   繁体   中英

Change the first index of each sublist in a list

Change the first index of each sublist in a list. from 1,2 , 3 ... for example -

data = [['45', 'gh', 'tg'], ['23', 'gf', 'gzs'], ['21', 'xzs', 'gd']]

I want to get

data = [[1, 'gh', 'tg'], [2, 'gf', 'gzs'], [3, 'xzs', 'gd']]

which means changing the first index of each sublist. I tried

for subs in data:
i = 0
subs[0] = i + 1

Can some one help me to build this?

There is simple code that you may be find as useful:

data = [['45', 'gh', 'tg'], ['23', 'gf', 'gzs'], ['21', 'xzs', 'gd']]


for i in range (len(data)):

     data[i][0] = i + 1

You can use a list comprehension using enumerate to get the index. i+1 is done to start the index from 1 because the default index starts from 0 in python enumerate.

enumerate returns the index and the individual elements of the enumerated list. j here will be the list and j[1] and j[2] will be the first and the second element respectively.

new_data = [[i+1, j[1], j[2]] for i, j in enumerate(data)]
# [[1, 'gh', 'tg'], [2, 'gf', 'gzs'], [3, 'xzs', 'gd']]

Another similar alternative is following where j[1:] refers to the rest of the list from second element until the last excluding the first. You then add the first index to create the final list.

new_data = [[i+1] + j[1:] for i, j in enumerate(data)]

Bazingaa's answer is probably the ideal solution, but here's another SUPER inefficient way using map . (I just think it's important to know about other solutions when solving a problem.)

list(map(lambda sublist: [data.index(sublist) + 1] + sublist[1:], data))
# => [[1, 'gh', 'tg'], [2, 'gf', 'gzs'], [3, 'xzs', 'gd']]

使用enumerate来迭代列表您可以传递参数枚举以从1开始编号,在这种情况下应从1开始

[[idx,lis[1],lis[2]] for idx,lis in enumerate(data,1)]

I find this more readable,

for index,l in enumerate(data):
    data[index][0] = index+1

print(data)

# output
[[1, 'gh', 'tg'], [2, 'gf', 'gzs'], [3, 'xzs', 'gd']]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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