python:基于IF条件的过滤器

2024-09-28 21:31:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用简单的python条件操作,目的是过滤值>;或等于零,并将过滤后的值存储在列表中

# make a object contained all clusters
clustering = d.clusterer.clustering_dict[cut_off]
# list of ignored objects
banned_conf=[]
for clust in clustering:
    clustStr = str(clustering.index(clust))
    clustStr = int(clustStr) + 1
    # get the value of energy for the clust
    ener=clust[0].energy
    # set up filter to ignore conformations with positive energies
    if ener > 0:
        print('Conformation in ' + str(clustStr) + ' cluster poses positive energy')
        banned_conf.append(ener)
        print('Nonsence: It is ignored!')
        continue
    elif ener == 0:
        print('Conformation in ' + str(clustStr) + ' cluster poses ZERO energy')
        banned_conf.append(ener)
        print('Very rare case: it is ignored!')
        continue
    #else:
        #print("Ain't no wrong conformations in "  + str(clustStr) + " cluster")

如何可以忽略所有值>;在同一IF语句中or=0(不带elif)?哪种过滤更好(使用elif还是在单个IF语句中)


Tags: ofingtconfenergyclusterprintclustering
2条回答

您可以使用>=同时测试这两个条件

for index, clust in enumerate(clustering, 1):
    ener = clust[0].energy
    if ener >= 0:
        print(f'Conformation in {index} cluster poses zero or positive energy, it is ignored')
        banned_conf.append(clust)

如果您想显示零能量和正能量的不同信息,那么您原来的方法会更好

我将使用filter函数:

lst = [0,1,-1,2,-2,3,-3,4,-4]
filtered = list(filter(lambda x: x >= 0, lst))
for ele in filtered:
    print(f'{ele} is >= 0')

或者,如果您不想使用lamda函数和过滤器,我会:

lst = [0,1,-1,2,-2,3,-3,4,-4]
filtered = []
for ele in lst:
    if ele >= 0:
        filtered.append(ele)
for ele in filtered:
    print(f'{ele} is >= 0')

或者您可以使用列表理解:

lst = [0,1,-1,2,-2,3,-3,4,-4]
filtered = [for ele in lst if ele >= 0]
for ele in filtered:
    print(f'{ele} is >= 0')

相关问题 更多 >