簡體   English   中英

排序的函數需要4個參數?

[英]sorted function takes 4 arguments?

我有一些有效的代碼。 問題是,輸出編號不正確。 我查看了sorted()函數,並認為這是我需要使用的功能,但是當我使用它時,它說sorted只能接受4個參數,我有6-7個。

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()))

如何在保持相同格式的同時對輸出進行排序?

謝謝

將數字放在一個序列中,這是sorted()工作方式:

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

然后在編寫時從s選擇值:

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

請注意,由於s包含數字,因此格式可能應為%d ,如圖所示,而不是%s (用於字符串)。

放在一起,您的程序應該類似於:

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個“新鮮”隨機數,並按每行排序。

嘗試這個:

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))

我將使用列表進行排序。

創建一個列表,對其進行排序,對其進行格式化。

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添加更多邏輯,例如刪除重復的值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM