This is regarding a number sorting program. I am not able to understand the syntax with the join
line.
#!/usr/bin/env python
import sys
ar=[]
for arg in sys.argv:
ar.append(arg)
ar.sort()
print " ".join('%s'%x for x in ar)
This is regarding a number sorting program. I am not able to understand the syntax with the join
line.
#!/usr/bin/env python
import sys
ar=[]
for arg in sys.argv:
ar.append(arg)
ar.sort()
print " ".join('%s'%x for x in ar)
'%s' % x for x in ar
is what is called a generator expression. It generates a bunch of '%s' % x
where x
is defined as each item in ar
." ".join(...)
puts a space between each item given to .join()
. When the generator is given, it puts a space between each item the generator generates. If ar
is not a list of strings, the generator converts each item to a string. Then, we use " ".join(...)
to put a space between each of those strings. sys.argv
is always a list of strings, so you don't need that generator expression. You could instead use " ".join(sys.argv)
. According to this answer, it would be more efficient to use a list comprehension anyway. You would also use str(x)
instead of "%s"%x
just because it's easier to read.
I agree that the join
line looks super funky.
" ".join(...)
will take a list (or any iterable) of arguments and create for you one string where all the arguments arguments are separated by one space.
In this case I would just pass in your sorted list ar
.
#!/usr/bin/env python
import sys
ar=[]
for arg in sys.argv:
ar.append(arg)
ar.sort()
print " ".join(ar)
Now we have two more problems:
sys.argv[1:]
instead of just sys.argv
.[1, 11, 13, 2, 3, 4, 5, 56, 9]
. To remedy this, I'd use ar.append(int(arg))
.