[英]How to process every nth element in each of this list of lists?
我有一個看起來像這樣的列表;
list_of_lists =
[
[1640, 4, 0.173, 0.171, 0.172, 472],
[1640, 5, 0.173, 0.171, 0.173, 259],
[1640, 6, 0.175, 0.173, 0.173, 180],
]
我想處理此列表列表中每個列表的第二個元素,以便將其替換為通過向其添加 1 創建的 2 個元素。 它看起來像這樣;
new_list_of_lists =
[
[1640, 5, 5, 0.173, 0.171, 0.172, 472],
[1640, 6, 6, 0.173, 0.171, 0.173, 259],
[1640, 7, 7, 0.175, 0.173, 0.173, 180],
]
如何使用 python 3.9 做到這一點? 謝謝你。
您可以使用列表理解:
list_of_lists =
[
[1640, 4, 0.173, 0.171, 0.172, 472],
[1640, 5, 0.173, 0.171, 0.173, 259],
[1640, 6, 0.175, 0.173, 0.173, 180],
]
output = [[x[0], x[1] + 1, x[1] + 1, x[2], x[3], x[4], x[5]] for x in list_of_lists]
print(output)
這打印:
[
[1640, 5, 5, 0.173, 0.171, 0.172, 472],
[1640, 6, 6, 0.173, 0.171, 0.173, 259],
[1640, 7, 7, 0.175, 0.173, 0.173, 180]
]
我建議使用列表“切片”將第二個元素(切片 [1:2])替換為 2 元素列表:
for list in list_of_lists:
list[1:2] = [list[1] + 1] * 2
第一種方法:單獨更新每個元素
list_of_lists[0][1] += 1
list_of_lists[1][1] += 1
list_of_lists[2][1] += 1
第二種方法:更新所有元素
for num in range(len(list_of_lists)):
list_of_lists[num][1] += 1
您可以使用列表推導和變量來告訴它應該處理哪個索引:
list_of_lists = [
[1640, 4, 0.173, 0.171, 0.172, 472],
[1640, 5, 0.173, 0.171, 0.173, 259],
[1640, 6, 0.175, 0.173, 0.173, 180],
]
i = 1
new_list_of_lists = [a[:i]+[a[i]+1]*2+a[i+1:] for a in list_of_lists]
print(new_list_of_lists)
[[1640, 5, 5, 0.173, 0.171, 0.172, 472],
[1640, 6, 6, 0.173, 0.171, 0.173, 259],
[1640, 7, 7, 0.175, 0.173, 0.173, 180]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.