Python: Filter List Values Based on Another List
You can use list comprehension to achieve this. Here's an example:
list1 = [1, 2, 3, 4, 5]
list2 = [3, 4, 5, 6, 7]
result = [x for x in list1 if x in list2]
print(result) # Output: [3, 4, 5]
In the above code, the list comprehension checks each element 'x' in 'list1' and only adds it to the 'result' list if it exists in 'list2'.
原文地址: https://www.cveoy.top/t/topic/m6M9 著作权归作者所有。请勿转载和采集!