为什么我的if语句不适用于长度> 1?

问题描述 投票:-1回答:1
associationRules.csv = #I'm only displaying some lines here for my case
,antecedents,consequents,confidence
19,"(LM = 20, SMOK = y)",(DIAB = n),0.5   
20,(LM = 20),"(DIAB = n, SMOK = y)",0.5
21,"(DIAB = n, RCA = 85, LM = 15)",(SMOK = y),1.0
175,(RCA = 85),(LAD = 40),0.6666666666666667
176,(LAD = 40),(RCA = 85),1.0
177,"(DIAB = y, CHOL = 200, SMOK = y)",(LAD = 90),0.6666666666666667
178,"(DIAB = y, CHOL = 200, LAD = 90)",(SMOK = y),1.0 
200,(LM = 20),"(RCA = 75, DIAB = n)",0.5
203,"(SEX = F, DIAB = y, SMOK = y)",(LM = 20),1.0
239,(CHOL = 200),"(DIAB = y, SMOK = y)",1.0

我正在遍历关联规则行,并且只想在以下情况下提取行:列“antecedent”只有数据集属于g1或g2。并且不属于y。意思是,只应提取行(175,176,203)。

y = ['CHOL = 200', 'LM = 20', 'LM = 25', 'LM = 30', 'LM = 15', 'LM = 35' ]

#g1 and g2 are the rest of other values of antecedents s.a: DIAB, RCA, LAD..etc 

我的代码仅在len(前提)== 1时有效,在len(前提)> 1时失败。

antecedents_list = []

for i, row in associationRules.iterrows():
    antecedents = row.iloc[0]

    flag1 = False
    flag2 = False
    single_antecedent = False

    for j, v in enumerate(antecedents): 

        if len(antecedents) == 1 and (v not in y): #print single items
            single_antecedent = True

        elif len(antecedents) > 1 and (v not in y):
            if v in g1:
                flag1 = True
            if v in g2:
                flag2 = True


    if single_antecedent or (flag1 and flag2):
     antecedents_list.append(antecedents)
     rules['antecedents'] = antecedents_list

我究竟做错了什么?谁能帮忙

python if-statement data-structures enumeration flags
1个回答
1
投票

如果你的意思是belongs to g1 or g2 onlyDOES NOT belong to yg1 g2y的其他值。我想你可以检查是否有任何属于y的元素。如果答案是否定的,那就是你想要的专栏,比如(175, 176, 203)

另外,我认为这里不需要len(antecedents) == 1的条件。你可以试试这个:

antecedents_list = []

for i, row in associationRules.iterrows():
    antecedents = row.iloc[0]

    flag = True
    for v in antecedents:
        # belong to y, break out
        if v in y:
            flag = False
            break

    # or more pythonic way
    # flag = all(v not in y for v in antecedents)

    if flag:
        antecedents_list.append(antecedents)
        rules['antecedents'] = antecedents_list

无法调试自己,你可以尝试一下。


如果你坚持你的代码版本,我可以告诉你哪里错了:

if single_antecedent or (flag1 and flag2):

这里应该改为flag1 or flag2

希望对您有所帮助,并在您有其他问题时发表评论。 :)

© www.soinside.com 2019 - 2024. All rights reserved.