簡體   English   中英

使用列表推導 Python 將值添加到數組列表的第一個索引

[英]Adding a value to the first index of a list of array by using a list comprehension Python

下面的 Vals 列表理解修改了Values ,以便對於第 n 行它索引數組值。 我如何能夠在Vals列表理解中添加一個增量,它在所有修改后的列表前面添加 100? 我只想修改列表理解 function 來做到這一點。

import numpy as np 

first_index_val = 100
Values = np.array([[130,123,135.3,139.05,156.08,163.88,173.72],
                  [130,123,135.3,139.05,156.08,163.88,173.72],
                  [130,123,135.3,139.05,156.08,163.88,173.72],
                  [130,123,135.3,139.05,156.08,163.88,173.72],
                  [130,123,135.3,139.05,156.08,163.88,173.72],
                  [130,123,135.3,139.05,156.08,163.88,173.72],
                  [130,123,135.3,139.05,156.08,163.88,173.72]])

Vals = np.array([arr[i:] for i,arr in enumerate(Values.tolist())])

Output:

[list([130.0, 123.0, 135.3, 139.05, 156.08, 163.88, 173.72])
 list([123.0, 135.3, 139.05, 156.08, 163.88, 173.72])
 list([135.3, 139.05, 156.08, 163.88, 173.72])
 list([139.05, 156.08, 163.88, 173.72]) list([156.08, 163.88, 173.72])
 list([163.88, 173.72]) list([173.72])]

預期 Output:

[list([100, 130.0, 123.0, 135.3, 139.05, 156.08, 163.88, 173.72])
 list([100, 123.0, 135.3, 139.05, 156.08, 163.88, 173.72])
 list([100, 135.3, 139.05, 156.08, 163.88, 173.72])
 list([100, 139.05, 156.08, 163.88, 173.72]) list([100, 156.08, 163.88, 173.72])
 list([100, 163.88, 173.72]) list([100, 173.72])]

只需添加到列表理解中。

Vals = np.array([100] + [arr[i:] for i,arr in enumerate(Values.tolist())])

這是我的看法,簡單而明確。

import numpy as np

first_index_val = 100
values = np.array([[130, 123, 135.3, 139.05, 156.08, 163.88, 173.72],
               [130, 123, 135.3, 139.05, 156.08, 163.88, 173.72],
               [130, 123, 135.3, 139.05, 156.08, 163.88, 173.72],
               [130, 123, 135.3, 139.05, 156.08, 163.88, 173.72],
               [130, 123, 135.3, 139.05, 156.08, 163.88, 173.72],
               [130, 123, 135.3, 139.05, 156.08, 163.88, 173.72],
               [130, 123, 135.3, 139.05, 156.08, 163.88, 173.72]])


flipped = np.flip(values, 1)

appended = np.array([np.append(x, first_index_val) for x in flipped])

print(np.flip(appended, 1))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM