2013-07-02 68 views
-1

我有一些代码可以工作。问题是,输出数字不合适。我查看了sorted()函数并相信这就是我需要使用的,但是当我使用它时,它说排序只能有4个参数,我有6-7个参数。排序函数需要4个参数?

print "Random numbers are: " 
for _ in xrange(10): 
    print rn(),rn(), rn(), rn(), rn(), rn(), rn() 


with open('Output.txt', 'w') as f: 
    f.write("Random numbers are: \n") 
    for _ in xrange(500): 
     f.write("%s,%s,%s,%s,%s,%s\n" % (rn(), rn(), rn(), rn(), rn(), rn())) 

如何对输出进行排序,同时保持与此格式相同的格式?

谢谢

回答

0

试试这个:

from random import randint 

def rn(): 
    return randint(1,49) 

with open('Output.txt', 'w') as f: 
    f.write("Random numbers are: \n") 
    for _ in xrange(10): 
     s = sorted(rn() for _ in xrange(6)) 
     f.write("{},{},{},{},{},{}\n".format(*s)) 
+0

完美的工作。谢谢。 – BubbleMonster

3

把数字序列中,这是sorted()作品有:

s = sorted([rn(), rn(), rn(), rn(), rn(), rn()]) 

然后从s书写时挑值:

f.write("%d,%d,%d,%d,%d,%d\n" % tuple(s)) 

注意,因为s保存号码,格式应该如图所示%d,而不是%s h是字符串。

将其组合在一起,你的程序应该是这样的:

with open('Output.txt', 'w') as f: 
f.write("Random numbers are: \n") 
for _ in xrange(500): 
    s = sorted([rn(), rn(), rn(), rn(), rn(), rn()]) 
    f.write("%d,%d,%d,%d,%d,%d\n" % tuple(s)) 

假设rn()函数返回一个随机数,这应该给你500线6“新鲜”的随机数,排序上的每一行。

+0

感谢您的代码。我添加了sorted()函数,但问题是,每行数字都是相同的。 – BubbleMonster

+0

@BubbleMonster将其添加到for循环中。 –

+0

@AshwiniChaudhary - 我做到了,我的代码看起来是这样的: 打印 “随机数是:” 为_中的xrange(10): \t小号排序=(RN(),RN(),RN() ('Output.txt','w')为f: f.write(“随机数字为:\ n”) for _in() xrange(10): \t f.write(“%d,%d,%d,%d,%d,%d \ n”%tuple(s)) – BubbleMonster

0

我会用一个列表进行排序。

创建一个列表,对其进行排序,格式化。

import random 

def get_numbers(): 
    return sorted([random.randint(1, 49) for _ in xrange(6)]) 

with open('Output.txt', 'w') as f: 
    f.write("Random numbers are: \n") 
    for _ in xrange(10): 
     f.write(','.join(map(str, get_numbers())) + '\n') 

现在您可以添加一些更多的逻辑get_numbers像删除重复的值。

+0

对不起,直到现在没有看到。这完美地完成了一切。你说得对,我现在只需要添加一个get_numbers函数。谢谢 – BubbleMonster

相关问题