# Throw out blank lines and commentswith open('file.txt', 'r') as lines:# From the inside out:# [s.partition('#')[0].strip() for s in lines]... Throws out comments# filter(lambda x: x!= '', [s.part... Filters out blank lines# y for y in filter... Converts filter object to listfile_contents = [y for y in filter(lambda x: x != '', [s.partition('#')[0].strip() for s in lines])]
whitelist = set(range(0, 100000000, 27))
input_list = list(range(0, 100000000))
proximal_list = list(filter(lambda x: x in whitelist,input_list))
proximal_list2 = [x for x in input_list if x in whitelist]
print(len(proximal_list))print(len(proximal_list2))
import cProfilefrom time import time
class BlockProfile:def __init__(self, profile_path):self.profile_path = profile_pathself.profiler = Noneself.start_time = None
def __enter__(self):self.profiler = cProfile.Profile()self.start_time = time()self.profiler.enable()
def __exit__(self, *args):self.profiler.disable()exec_time = int((time() - self.start_time) * 1000)self.profiler.dump_stats(self.profile_path)
whitelist = set(range(0, 100000000, 27))input_list = list(range(0, 100000000))
with BlockProfile("/path/to/create/profile/in/profile.pstat"):proximal_list = list(filter(lambda x: x in whitelist,input_list))
proximal_list2 = [x for x in input_list if x in whitelist]
print(len(proximal_list))print(len(proximal_list2))
在您的情况下,它只是一个简单的过滤方法,两者都可以完成,但我更喜欢第一个my_list = [x for x in my_list if x.attribute == value],因为它看起来很简单,不需要任何特殊的语法。任何人都可以理解这个命令并在需要时进行更改。(虽然第二种方法也很简单,但对于初学者来说,它仍然比第一种方法更复杂)