Home > Blockchain >  How can i write for&if-else statement using only one line?
How can i write for&if-else statement using only one line?

Time:01-12

  • Make List a String: Let's make the list ["Life", "is", "too", "short"] into a "Life is too short" string and print it out.

First, Let me tell you i know the way to solve the problem using join() method.

I wanted to solve this using another method, and i used for statement as below.

liszt = ['Life', 'is', 'too', 'short']
restr = ''
for i in liszt: restr  = i ' ' if liszt.index(i) != 3 else restr  = i
print(restr)

How can i correct this in valid syntax? or... is there any simpler way to code this than mine?

At that time, I intended to express same thing as below using one line. But editor told me it's invalid syntax.

liszt = ['Life', 'is', 'too', 'short']
restr = ''
for i in liszt:
    if liszt.index(i) != 3:
        restr  = i ' '
    else:
        restr  = i
print(restr)

CodePudding user response:

You can use conditional assignment inside a one-line for loop like this:

for i in liszt: restr  = i   ' ' if liszt.index(i) != 3 else i

CodePudding user response:

As others have mentioned, one-liners aren't always better/faster/more readable. Here's a solution using functools.reduce.

from functools import reduce
liszt = ['Life','is','too','short']
restr = reduce(lambda x,y: x   ' '   y, liszt)
print(restr)

Another without importing:

restr = ''
for i,word in enumerate(liszt): restr  = word   (' ' if i != len(liszt)-1 else '')

Another one using the walrus operator:

restr = ''
[restr := restr   (' ' if i else '')   word for i,word in enumerate(liszt)]

Or using the indexing in your question:

restr = ''
for i in liszt: restr  = i (' ' if liszt.index(i) != len(liszt)-1 else '')

CodePudding user response:

You could use str.translate() method to remove the unwanted characters from the strings in liszt by calling str.maketrans to create a translation table to remove square brackets, commas and quotes.

import string

liszt = ['Life', 'is', 'too', 'short']
restr = str(liszt).translate(str.maketrans("", "", "[],\'\'"))
print(restr)

Output:

Life is too short

CodePudding user response:

using recurssion here is code in one liner

nstring = "this is a program running on computer"
nstring = "this is a program running on computer".split()
print(nstring)
# output -> ['this', 'is', 'a', 'program', 'running', 'on', 'computer']
def new_join_method(string): return '' if (len(string) == 0) else f"{string[0]} {func(string[1:])}".strip()
 
solution = new_join_method(nstring)
print(solution)
# output. --> 'this is  a  program  running  on  computer'

CodePudding user response:

you can use join function for exactly this purpose

print(" ".join(liszt))
  • Related