2013-07-02 67 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

相關問題