简体   繁体   中英

python: filter based on IF condition

I am operating with simple python condition aimed at filtering of the values > or equal to zero, and store filtered values in the list

# 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")

How would it be possible to ignore all values > or = 0 within the same IF statement (without elif)? Which filtering would be better (with elif or in single IF statement)?

You can use >= to test both conditions at once.

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)

Your original method is better if you want to show a different message for zero and positive energy.

I would use the 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')

Or if you don't want to use lamda function and filter I would do:

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

Or you can use list comprehension:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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