Creating an IF statement in Python that looks at previous IF statement output

前端 未结 3 928
忘掉有多难
忘掉有多难 2021-01-20 16:30

I am having difficulty creating an IF statement that does the following:

  • If C1 = Buy, then Buy
  • If C2 = Sell, then Sell
  • If C1 & C2 = nan,
3条回答
  •  盖世英雄少女心
    2021-01-20 17:02

    Instead of doing the previous if statement, you can simply look at what has been previously put into the c3 list (as that is a result of the previous if statement).

    Here is an example of how you can achieve this in python:

    c1 = ["Buy", "nan", "nan", "nan", "Buy", "nan", "nan", "nan", "nan", "Buy", "nan"]
    c2 = ["nan", "nan", "Sell", "nan", "nan", "Sell", "Sell", "nan", "nan", "nan", "Sell"]
    
    c3 = []
    for index in range(len(c1)):
        if c1[index] == "Buy":
            c3.append("Buy")
        elif c2[index] == "Sell":
            c3.append("Sell")
        elif c1[index] == "nan" and c2[index] == "nan": # Implied if reached this point (so else would also suffice here)
            c3.append(c3[index-1]) # look at previous result in list
    print(c3)
    

    Output:

    ['Buy', 'Buy', 'Sell', 'Sell', 'Buy', 'Sell', 'Sell', 'Sell', 'Sell', 'Buy', 'Sell']

提交回复
热议问题