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 07:46:22 浏览: 19
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.
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)