Seite 1 von 1

maintaining list order

Verfasst: Mittwoch 5. Juni 2019, 10:27
von tutu10
Simple comparison thingy. I have two lists and I want to compare if a value is larger than a value in the other list. The result is correct, however the structure is broken, I want the structure of the result list the same as the elements list.

Code: Alles auswählen

comparelist = [0, 3000, 6000]
elements = [[3], [4, 400], [3,4222]]
result = []
 
for element in elements:    
    for e in element:
        t = []
        count = -1       
        for c in comparelist:
            if e > c:
                count +=1
            else:
                t.append(comparelist[count])
                break       
    result.append(t)
print(result)
 
#Results in [[0], [0], [0], [0], [3000]]
 
#I need [[0], [0, 0], [0, 3000]]
Somewhat more pythonic way to write things ( I guess ... still learning )

Code: Alles auswählen

comparelist = [0, 3000, 6000]
elements = [[3], [4, 400], [3,4222]]
result = []
 
for element in elements:    
    for e in element:
        t = []           
        for index, value in enumerate(comparelist,-1):
            if e > value:
                pass
            else:
                t.append(comparelist[index])
                break       
    result.append(t)
print(result)
What am I doing wrong / what am I missing?

Re: maintaining list order

Verfasst: Mittwoch 5. Juni 2019, 11:00
von noisefloor
Hi,

@tutu10: in case you did not realize - the language of this board is German, not English. Although it's not impossible that you get an answer, it a bit more unlikely.

Gruß, noisefloor

Re: maintaining list order

Verfasst: Mittwoch 5. Juni 2019, 11:43
von __blackjack__
@tutu10: Could you explain what you actually want to do/solve here? I don't understand why/how you would arrive at ``[[0], [0, 0], [0, 3000]]`` as result for the given input data. The structure seems to be the same as ``elements`` but why/how do you want to decide if an element is 0 or something different?

Re: maintaining list order

Verfasst: Mittwoch 5. Juni 2019, 14:37
von ThomasL
Just initialize the empty list "t" at the right spot :-)

Code: Alles auswählen

comparelist = [0, 3000, 6000]
elements = [[3], [4, 400], [3,4222]]
result = []
 
for element in elements:
    t = []
    for e in element:
        for index, value in enumerate(comparelist,-1):
            if e > value:
                pass
            else:
                t.append(comparelist[index])
                break
    result.append(t)
    
print(result)