Take a look inside file1.txt and file2.txt. They each contain a bunch of numbers, each number on a new line. # Write your code above 👆 print(result) You are going to create a list called result which contains the numbers that are common in both files. e.g. if file1.txt contained: 1 2 3 and file2.txt contained: 2 3 4 result = [2, 3] IMPORTANT: The result should be a list that contains Integers, not Strings. Try to use List Comprehension instead of a Loop. Example Output [3, 6, 5, 33, 12, 7, 42, 13]
时间: 2024-03-17 22:46:22 浏览: 371
读取txt文件中的数字并输出
Sure, I understand your question. Here is the code to create a list called result which contains the numbers that are common in both files using List Comprehension:
```
with open('file1.txt', 'r') as file1:
file1_numbers = [int(line.strip()) for line in file1]
with open('file2.txt', 'r') as file2:
file2_numbers = [int(line.strip()) for line in file2]
result = [number for number in file1_numbers if number in file2_numbers]
print(result)
```
This code reads the numbers from the two files, converts them into integers and creates two lists file1_numbers and file2_numbers respectively. Then it creates a new list called result using List Comprehension, which contains only the numbers that are common in both files. Finally, it prints the result list.
阅读全文