繁体   English   中英

python:根据 IF 条件过滤

[英]python: filter based on IF condition

我正在使用简单的 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 语句(没有 elif)中忽略所有 > 或 = 0 的值? 哪种过滤会更好(使用 elif 或在单个 IF 语句中)?

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

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 function:

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 function 和过滤器,我会这样做:

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')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM