简体   繁体   中英

Rendering a list to a sublist in Python

I have a list J and an array MaxPr . I am creating a new list Max Pr new with a loop shown below. But I want to have a sublist within this list. I present the current and expected outputs.

import numpy as np
arMaxPrnew=[]

J=[[1, 2, 8, 9, 11, 12, 13, 16, 17, 18, 21, 24, 25, 26, 27, 31, 33, 36, 37, 38]] 

MaxPr=np.array([423.056174 , 368.757486 , 339.165087 , 339.165087 , 423.056174 ,
       423.056174 , 368.757486 , 339.165087 , 339.165087 , 423.056174 ,
       368.757486 , 339.165087 , 339.165087 , 294.817814 , 313.653565 ,
       313.653565 , 276.03611  ,   0.       , 294.817814 , 313.653565 ,
       276.03611  ,  18.388115 , 294.817814 , 294.817814 , 294.817814 ,
       197.811705 ,  18.388115 , 294.817814 , 294.817814 , 197.811705 ,
        37.2027264, 294.817814 , 294.817814 , 294.817814 , 114.343795 ,
        37.2027264, 294.817814 , 294.817814 , 114.343795 ,  37.2027264])


for i in range(0,len(J[0])):
    MaxPrnew=MaxPr[J[0][i]]
    arMaxPrnew.append(MaxPrnew)
    MaxPrnew=list(arMaxPrnew) 
print("Max Pr new =",MaxPrnew) 

The current output is

Max Pr new = [368.757486, 339.165087, 339.165087, 423.056174, 339.165087, 339.165087, 294.817814, 276.03611, 0.0, 294.817814, 18.388115, 294.817814, 197.811705, 18.388115, 294.817814, 294.817814, 294.817814, 294.817814, 294.817814, 114.343795]

The expected output is

Max Pr new = [[368.757486, 339.165087, 339.165087, 423.056174, 339.165087, 339.165087, 294.817814, 276.03611, 0.0, 294.817814, 18.388115, 294.817814, 197.811705, 18.388115, 294.817814, 294.817814, 294.817814, 294.817814, 294.817814, 114.343795]]

You used class list (iterable) to generate a list from iterable arMaxPrnew . It simply converts iterable to list. If you want a list of lists, you have to use another way

    MaxPrnew = list()
    MaxPrnew.append(arMaxPrnew)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM