我有一個看起來像這樣的串列;
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 做到這一點?謝謝你。
uj5u.com熱心網友回復:
您可以使用串列理解:
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]
]
uj5u.com熱心網友回復:
我建議使用串列“切片”將第二個元素(切片 [1:2])替換為 2 元素串列:
for list in list_of_lists:
list[1:2] = [list[1] 1] * 2
uj5u.com熱心網友回復:
第一種方法:單獨更新每個元素
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
uj5u.com熱心網友回復:
您可以使用串列推導式和一個變數來告訴它應該處理哪個索引:
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]]
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/392883.html
