[英]how to fix this number sorting python code so that it works correctly
This is regarding a number sorting program. 这是关于数字排序程序的。 I am not able to understand the syntax with the
join
line. 我无法理解
join
行的语法。
#!/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 . '%s' % x for x in ar
是生成器表达式 。 It generates a bunch of '%s' % x
where x
is defined as each item in ar
. 它生成一堆
'%s' % x
,其中x
定义为ar
每个项目。 " ".join(...)
puts a space between each item given to .join()
. " ".join(...)
在给.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. 如果
ar
不是字符串列表,则生成器会将每个项目转换为字符串。 Then, we use " ".join(...)
to put a space between each of those strings. 然后,我们使用
" ".join(...)
在每个字符串之间放置一个空格。 sys.argv
is always a list of strings, so you don't need that generator expression. sys.argv
始终是字符串列表,因此您不需要该生成器表达式。 You could instead use " ".join(sys.argv)
. 您可以改为使用
" ".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. 您还可以使用
str(x)
代替"%s"%x
,因为它更易于阅读。
I agree that the join
line looks super funky. 我同意
join
行看起来非常时髦。
" ".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. " ".join(...)
将获取参数列表(或任何可迭代的参数),并为您创建一个字符串,其中所有参数参数均由一个空格分隔。
In this case I would just pass in your sorted list ar
. 在这种情况下,我只是传递您的排序列表
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
. sys.argv[1:]
而不是sys.argv
。 [1, 11, 13, 2, 3, 4, 5, 56, 9]
. [1, 11, 13, 2, 3, 4, 5, 56, 9]
1、11、13、2、3、4、5、56、9]的排序。 To remedy this, I'd use ar.append(int(arg))
. ar.append(int(arg))
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.