簡體   English   中英

如何將輸出保存為 .txt 文件?

[英]How to save output as a .txt file?

這是我的代碼:

def generate_random_number_list_10(len_of_elements):

    my_list=[random.randint(1,100) for x in range (len_of_elements)]
    return my_list

def generate_list_consist_of_10_smaller_list(amount_of_list,len_of_elements,variable):

    big_list=[generate_random_number_list_10(len_of_elements) for x in range (amount_of_list)]
    print (*big_list,sep="\n")
    if variable%2 == 0:
        print("Even variable has been entered: "+repr(variable)+" so program have filtered all even number from the list ")
        filtered_list = [list(filter(lambda x: x%2==0, num)) for num in big_list]
        print (*filtered_list,sep="\n")
    if variable%2 != 0:
        print("Odd variable has been entered: "+repr(variable)+" so program have filtered all odd number from the list ")
        filtered_list = [list(filter(lambda x: x%2!=0, num)) for num in big_list]
        print (*filtered_list,sep="\n")

這是我的輸出

[96, 36, 19, 60, 90, 75, 30, 8, 98, 17]
[20, 81, 53, 65, 80, 5, 57, 55, 45, 41]
[80, 82, 49, 66, 47, 50, 87, 94, 78, 7]
[9, 64, 71, 95, 77, 53, 45, 52, 70, 69]
[13, 17, 62, 87, 27, 15, 56, 27, 96, 55]
[33, 83, 96, 65, 65, 80, 19, 79, 25, 95]
[38, 54, 98, 87, 98, 32, 20, 74, 93, 41]
[74, 45, 3, 59, 62, 83, 71, 35, 75, 7]
[14, 2, 54, 93, 83, 25, 22, 61, 90, 82]
[53, 99, 40, 66, 2, 13, 40, 17, 32, 11]

已輸入偶數變量:8 所以程序已從列表中過濾掉所有偶數

[96, 36, 60, 90, 30, 8, 98]
[20, 80]
[80, 82, 66, 50, 94, 78]
[64, 52, 70]
[62, 56, 96]
[96, 80]
[38, 54, 98, 98, 32, 20, 74]
[74, 62]
[14, 2, 54, 22, 90, 82]
[40, 66, 2, 40, 32]

如何將輸出保存為 .txt 文件。 我想以最簡單的方式做到這一點。 我的同事說我可以使用上下文管理器,但我不知道它是如何工作的。 有人也可以幫我解決這個問題。

如果我有兩個 if 條件,我是否必須在兩個條件中添加一些內容? 無論變量是什么(偶數或奇數),是否有任何方法可以只寫輸出

做:

with open("file.txt", "w") as file:
  for element in filtered_list:
    file.write(element + "\n")

暫無
暫無

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

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