简体   繁体   English

使用列表推导 Python 将值添加到数组列表的第一个索引

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

The Vals list comprehension below modifies Values such that for the number of nth rows it indexes the array values as such.下面的 Vals 列表理解修改了Values ,以便对于第 n 行它索引数组值。 How would I be able to add an increment to the Vals list comprehension where it adds 100 in front of all of the modified lists?我如何能够在Vals列表理解中添加一个增量,它在所有修改后的列表前面添加 100? I want to only modify the list comprehension function to do that.我只想修改列表理解 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: 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])]

Expected Output:预期 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])]

Just add in the addition to the list comprehension.只需添加到列表理解中。

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

Here is my take on it, simple and declarative.这是我的看法,简单而明确。

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