Python Forum
how to create pythonic codes including for loop and if statement? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: how to create pythonic codes including for loop and if statement? (/thread-31760.html)



how to create pythonic codes including for loop and if statement? - aupres - Jan-02-2021

I am a newbie on python coding. Below are my legacy python codes.

for i, df_list in enumerate(df_list_of_list):
    for j, df in enumerate(df_list):
        if i == 0 & j ==0:
            fred.writeCsv2Hdfs('earnings.csv', df)  # create file successfully
        else:    
            fred.appendCsv2Hdfs('earnings.csv', df) # append file successfully
        
        df.to_csv('outputs/earnings.csv', mode='a', index_label='date', header=(i==0|j==0))   # writing results onto local file
But I want to change these codes to more pythonic codes. First, I tried to use lambda statement like below,

def writeDFHdfs(filename, df_list):
    f = lambda i, df: fred.writeCsv2Hdfs(filename, df) if i == 0 else fred.appendCsv2Hdfs(filename, df), df_list
But I am afraid I have no idea here in generating pythonic codes including both for loop and if statement. How can these multi line codes be changed to one or two lines? Any reply will be really thankful.


RE: how to create pythonic codes including for loop and if statement? - Gribouillis - Jan-02-2021

The only unpythonic parts that I see here are if i==0 & j==0 which should be if not(i or j) and i==0|j==0 which should be not(i and j). Note that & and | are bitwise operators and not logical operators. The result is also different because they have different levels of operator precedence. For example
>>> 0==0 & 7==0
True
>>> 0==0 and 7==0
False
Writing code on a single line does not necessarily give better Python code, and it is not necessarily 'pythonic'. I'm not sure there is a better solution here.