-2

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

[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. 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? Is there any method to write just output regardless of what the variable will be (even or odd)

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • 2
    Does this answer your question? [Correct way to write line to file?](https://stackoverflow.com/questions/6159900/correct-way-to-write-line-to-file) – mkrieger1 Mar 19 '20 at 14:38
  • 1
    It's explained in the official Python tutorial: https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files – mkrieger1 Mar 19 '20 at 14:41
  • 1
    a piece of advice, you live in 2020 where seemingly infinite information is at your fingertips. It is much faster for you to google "how to do X" than to just write a question on SO and wait for somebody to reply. – searchengine27 Mar 19 '20 at 14:42

1 Answers1

1

do:

with open("file.txt", "w") as file:
  for element in filtered_list:
    file.write(element + "\n")
Sven
  • 1,014
  • 1
  • 11
  • 27