【问题标题】:How to split the final value in arrays into its own array?如何将数组中的最终值拆分为自己的数组?
【发布时间】:2025-12-04 12:25:01
【问题描述】:

我有一个数组数组,每个数组包含 5 个值。我想将整个数组中每个数组的最后一个值拆分为自己的数组,但我想不出最好的方法。

FeatureVectors = [[4, 0.001743713493735165, 0.6497055601752815, 90.795723552739275, 2], [4, 0.0460937435599832, 0.19764217920409227, 90.204147248752378, 2], [1, 0.001185534503063044, 0.3034913722821194, 60.348908179729023, 2], [1, 0.015455289770298222, 0.8380914254332884, 109.02120657826231, 2], [3, 0.0169961646358455, 41.36919146079211, 136.83829993466398, 2]]

在这种情况下,数组中的最后一个值都是 2,但情况并非总是如此。

我想得到这个:

FeatureVectors = [[4, 0.001743713493735165, 0.6497055601752815, 90.795723552739275], [4, 0.0460937435599832, 0.19764217920409227, 90.204147248752378], [1, 0.001185534503063044, 0.3034913722821194, 60.348908179729023], [1, 0.015455289770298222, 0.8380914254332884, 109.02120657826231], [3, 0.0169961646358455, 41.36919146079211, 136.83829993466398]]

Labels = [2, 2, 2, 2, 2]

谢谢

【问题讨论】:

  • 你能提供一些你已经尝试过的代码吗?
  • PEP-8;不要使用FeatureVectorsLabels 作为变量名。请改用feature_vectorslabels

标签: python arrays split


【解决方案1】:

使用以下方法(使用列表理解):

FeatureVectors = [[4, 0.001743713493735165, 0.6497055601752815, 90.795723552739275, 2], [4, 0.0460937435599832, 0.19764217920409227, 90.204147248752378, 2], [1, 0.001185534503063044, 0.3034913722821194, 60.348908179729023, 2], [1, 0.015455289770298222, 0.8380914254332884, 109.02120657826231, 2], [3, 0.0169961646358455, 41.36919146079211, 136.83829993466398, 2]]
FeatureVectors, Labels = ([i[:-1] for i in FeatureVectors], [i[-1] for i in FeatureVectors])

print(FeatureVectors, Labels, sep='\n')

输出(连续):

[[4, 0.001743713493735165, 0.6497055601752815, 90.79572355273928], [4, 0.0460937435599832, 0.19764217920409227, 90.20414724875238], [1, 0.001185534503063044, 0.3034913722821194, 60.34890817972902], [1, 0.015455289770298222, 0.8380914254332884, 109.02120657826231], [3, 0.0169961646358455, 41.36919146079211, 136.83829993466398]]
[2, 2, 2, 2, 2]

【讨论】:

    【解决方案2】:

    一口气搞定:

    Labels = [vector.pop() for vector in FeatureVectors]
    

    【讨论】: