1

my question is how do I scan "my_list" for "comp" and change the associated time value from 200 to "t" only if 200 is less than t?

t = 3000
comp = 'C1'
my_list = [[200, 'C1'],[4000, 'C2']] 

Output:

my_list = [[3000, 'C1'],[4000, 'C2']] 

The opposite could be done with this scenario as the list shouldn't change as "t" is less than "5000":

t = 3000
comp = 'C1'
my_list = [[5000, 'C1'],[4000, 'C2']] 
2
  • Hence, The mutables. Commented Mar 7, 2019 at 13:06
  • you may consider accepting an answer that helped you understand and solve your problem! meta.stackexchange.com/questions/5234/… Commented Mar 8, 2019 at 15:32

2 Answers 2

1

Try this:

my_list = [[t,k[1]] if( k[1]==comp and k[0]<t ) else k for k in my_list]
Sign up to request clarification or add additional context in comments.

1 Comment

It would fail for: my_list = [[200, 'C3'],[4000, 'C2']]
0

Using deepcopy:

t = 3000
comp = 'C1'
my_list = [[200, 'C1'],[4000, 'C2']]

for e in my_list[:]:
    if comp in e:
        if e[0] < t:
            e[0] = t

print(my_list)

Eventually, one-liner:

print([[t,e[1]] if e[1] == comp and e[0]<t else e for e in my_list])

OUTPUT:

[[3000, 'C1'], [4000, 'C2']]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.