我有这个清单
[['a', 'a', 'a', 'a'],
['b', 'b', 'b', 'b', 'b'],
['c', 'c', 'c', 'c', 'c']]
我希望从第二行开始连接每行中的第2和第3个元素,以形成如下内容:
[['a', 'a', 'a', 'a'],
['b', 'bb', 'b', 'b'],
['c', 'cc', 'c', 'c']]
当我对每一行都这样做时似乎工作正常:
for index, item in enumerate(list_of_lines, start=0):
list_of_lines[index][1:3] = [''.join(item[1:3])]
但是当我从第二行开始时 - 我有“列表索引超出范围”错误:
for index, item in enumerate(list_of_lines, start=1):
list_of_lines[index][1:3] = [''.join(item[1:3])]
答案 0 :(得分:4)
致电时
enumerate(list_of_lines, start=1)
,它生成的对不是
1 ['b', 'b', 'b', 'b', 'b']
2 ['c', 'c', 'c', 'c', 'c']
,而是
1 ['a', 'a', 'a', 'a']
2 ['b', 'b', 'b', 'b', 'b']
3 ['c', 'c', 'c', 'c', 'c']
也就是说,起始值表示应该使用的第一个索引,而不是第一个使用的元素。
也许另一种方法是:
for (index, item) in list(enumerate(list_of_lines))[1:]:
list_of_lines[index][1:3] = [''.join(item[1:3])]
答案 1 :(得分:3)
您可以使用iter()
内置显式创建一个iterable,然后调用`next(iterable)来使用一个项。最终结果是这样的:
line_iter = iter(list_of_lines[:])
# consume first item from iterable
next(line_iter)
for index, item in enumerate(line_iter, start=1):
list_of_lines[index][1:3] = [''.join(item[1:3])]
注意第一行上的切片,一般来说改变你正在迭代的东西是个坏主意,所以切片只是在构造迭代器之前克隆列表,因此可以安全地改变原始的list_of_lines。
答案 2 :(得分:0)
这里使用enumerate()没有太多优点...您可以简单地.pop()
从内部列表中选择第n个项目。为了循环数据,从索引1开始,然后将第二个值(弹出)添加到内部列表的第一个元素中:
data = [['a', 'a', 'a', 'a'],
['b', 'b', 'b', 'b', 'b'],
['c', 'c', 'c', 'c', 'c']]
for row in range(1,len(data)): # apply to 1st to n-th inner list by index
item = data[row].pop(2) # remove the 2nd item from inner list
data[row][1] += item # add it to the 1st of inner list
print(data)
输出:
[['a', 'a', 'a', 'a'],
['b', 'bb', 'b', 'b'],
['c', 'cc', 'c', 'c']]
请参阅list.pop(index)