简体   繁体   English

如何将输出保存为 .txt 文件?

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

This is my code:这是我的代码:

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

This is my output这是我的输出

[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]

Even variable has been entered: 8 so program have filtered all even number from the list已输入偶数变量: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]

How to save output as a .txt file.如何将输出保存为 .txt 文件。 I want to do it in the easiest way.我想以最简单的方式做到这一点。 My colleague said I could use Context Manager but I don't know how it works.我的同事说我可以使用上下文管理器,但我不知道它是如何工作的。 Can somebody help me in this matter too.有人也可以帮我解决这个问题。

If I have two if conditions, do I have to add something in both conditions?如果我有两个 if 条件,我是否必须在两个条件中添加一些内容? Is there any method to write just output regardless of what the variable will be (even or odd)无论变量是什么(偶数或奇数),是否有任何方法可以只写输出

do:做:

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