0

how can I get these loops and if statements into a comprehension?

raw = [['-', 'bla'], ['-', 'la'], ['=', 'bla']]

for one in raw:
    if one[0] == '-':
        for two in raw:
            if two[1] == one[1] and two[0] == '=': two[0] = '--'

So far:

[two+one for two in raw for one in raw]

But not sure where to put the if statements:

if one[0] == '-' and if two[1] == one[1] and two[0] == '=': two[0] = '--'

3
  • What is your desired ouput? Commented Mar 19, 2018 at 1:38
  • the example code returns raw as [['-', 'bla'], ['-', 'la'], ['--', 'bla']] Commented Mar 19, 2018 at 1:43
  • 1
    I've answered based on your desired output, as your logic is confusing. Commented Mar 19, 2018 at 1:49

2 Answers 2

2

A simple list comprehension should be sufficient:

raw = [['-', 'bla'], ['-', 'la'], ['=', 'bla']]

res = [['--' if (i != '-') and (['-', j] in raw) else i, j] for i, j in raw]

Result:

[['-', 'bla'], ['-', 'la'], ['--', 'bla']]
Sign up to request clarification or add additional context in comments.

3 Comments

I need raw [2]'s '=' value to change to -- only if an iteration of its companion string 'bla' with - exists ..... so the result will be ... if any bla exists with the - ... then all other blas that dont have - will have --
thanks for this. Out of curiosity, if i returns ['-', '-', '='] and j returns ['bla', 'la', 'bla'] ... how is every bla asking every other bla (and la) if it has a - value?
oh it's the in raw part!
0

You can set item in list comprehension ,

Your code:

for one in raw:
    if one[0] == '-':
        for two in raw:
            if two[1] == one[1] and two[0] == '=': two[0] = '--'

convert to list comprehension :

[[two.__setitem__(0,'--') if two[1]==one[1] and two[0]=='=' else two for two in raw] if one[0]=='-' else one for one in raw]
print(raw)

output:

[['-', 'bla'], ['-', 'la'], ['--', 'bla']]

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.