[英]Inserting value to every nth element in list of lists
我有以下方式的列表列表:
[[45.0, 58.0, 45.0, 520.0],
[45.0, 58.0, 754.0, 58.0],
[302.0, 58.0, 302.0, 520.0],
[563.0, 58.0, 563.0, 520.0],
[626.0, 58.0, 626.0, 257.0],
[754.0, 58.0, 754.0, 321.0],
[563.0, 159.0, 754.0, 159.0],
[626.0, 257.0, 754.0, 257.0],
[45.0, 260.0, 110.0, 260.0],
[302.0, 260.0, 563.0, 260.0],
[629.0, 321.0, 629.0, 520.0],
[45.0, 520.0, 629.0, 520.0],
[110.0, 58.0, 110.0, 322.0],
[45.0, 129.0, 110.0, 129.0],
[45.0, 322.0, 302.0, 322.0],
[563.0, 321.0, 754.0, 321.0],
[299.0, 520.0, 299.0, 581.0],
[299.0, 581.0, 562.0, 581.0],
[562.0, 520.0, 562.0, 581.0],
[563.0, 450.0, 629.0, 450.0]]
有沒有辦法可以將元素2
添加到列表中的每個第二個索引?
所以結果看起來像:
[[45.0, 58.0, 2, 45.0, 520.0, 2],
[45.0, 58.0, 2, 754.0, 58.0, 2],
[302.0, 58.0, 2, 302.0, 520.0, 2],
[563.0, 58.0, 2, 563.0, 520.0, 2],
.
.
.
.
這是您的問題的一種解決方案,使用 python 列表屬性
def insert_in_position(_list, element, position):
for i in range(len(_list)):
_list[i] = _list[i][:position]+[element]+_list[i][position:]
return _list
您可以使用insert()
、 append()
和List Comprehension 。
your_list = [[45.0, 58.0, 45.0, 520.0],
[45.0, 58.0, 754.0, 58.0],
...
[562.0, 520.0, 562.0, 581.0],
[563.0, 450.0, 629.0, 450.0]]
new_list = [x.insert(2, 2) or x.append(2) or x for x in your_list]
print(new_list)
# result:
[[45.0, 58.0, 2, 45.0, 520.0, 2],
[45.0, 58.0, 2, 754.0, 58.0, 2],
...
[562.0, 520.0, 2, 562.0, 581.0, 2],
[563.0, 450.0, 2, 629.0, 450.0, 2]]
您也可以查看此有用鏈接: 將項目附加到列表理解中的列表。
更多pythonic方式:
data = [[45.0, 58.0, 45.0, 520.0],
[45.0, 58.0, 754.0, 58.0],
...
[562.0, 520.0, 562.0, 581.0],
[563.0, 450.0, 629.0, 450.0]]
#Directly appending an element to item will impact original dataset,
#Since list is reference data structure,
for item in data:
item.append(2)
print(data)
[[45.0, 58.0, 2, 45.0, 520.0, 2],
[45.0, 58.0, 2, 754.0, 58.0, 2],
...
[562.0, 520.0, 2, 562.0, 581.0, 2],
[563.0, 450.0, 2, 629.0, 450.0, 2]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.