简体   繁体   中英

One-liner to print two statements in a for-loop in one line

How can I write this code in one line? The concept is that you should:

  • get one input from the user and check if the (ASCII form of the character) - 97 is divisible by 2 or not
    • if yes, you should print the original form of the character
    • else, you should print the upper case form of the character.
  • last, you should reverse the answer.
  • Example, if the input is alexander , the output should be eeaa X R NLD
  • But it should be in one line and only one, I came up with a solution but it was 3 lines, I don't know what to do next.

This is the code I came up with so far:

h = []
for i in input() : h.append(i.lower() if (ord(i) - 97) % 2 == 0 else i.upper())
print(*sorted(h, reverse=True))

The original code for the question, which you should convert to one line is:

input_string = str(input())
array = []
for i in range(len(input_string)):
    if (ord(input_string[i]) - 97) % 2 == 0:
        array.append(input_string[i])
    else:
        array.append(input_string[i].upper())
array.sort(reverse=True)
answer = ' '.join(array)
print(answer)

List comprehension (I did not check your code, only rewrite it):

h = []
for i in input() : h.append(i.lower() if (ord(i) - 97) % 2 == 0 else i.upper())
print(*sorted(h, reverse=True))

print(*sorted([i.lower() if (ord(i)-97)%2 == 0 else i.upper() for i in input() ], reverse=True))

To quote your question:

you should print the original form of the character

That is not what the code does at the moment, just saying so you are aware.

after reading your deleted comment:

And if you are wondering about the if and else in list comprehension:

You can put it in your list, but if that was your problem (the actual question apparently) then I would suggest to use google, there are plenty of examples where this is used.: if/else in a list comprehension , https://towardsdatascience.com/a-gentle-introduction-to-flow-control-loops-and-list-comprehensions-for-beginners-3dbaabd7cd8a , https://pythonguides.com/python-list-comprehension-using-if-else/

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