简体   繁体   English

更改列表中每个子列表的第一个索引

[英]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 - 从1,2,3 ...例如-

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. i+1是为了从1开始索引,因为在python枚举中默认索引从0开始。

enumerate returns the index and the individual elements of the enumerated list. enumerate返回索引和枚举列表的各个元素。 j here will be the list and j[1] and j[2] will be the first and the second element respectively. 这里的j将是列表, j[1]j[2]将分别是第一个和第二个元素。

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. 接下来是另一个类似的替代方法,其中j[1:]引用列表中从第二个元素到最后一个元素(不包括第一个元素)的其余部分。 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 . Bazingaa的答案可能是理想的解决方案,但这是使用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']]

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

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