簡體   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