Home > Enterprise >  How to simplify slightly different if statements to one in python
How to simplify slightly different if statements to one in python

Time:12-30

I would like to simplify this code and not repeat the if not statement and the print. Only one condition is being added in the first case curAccession == data[5] and the print is exactly the same. Is there any way to achieve this with a flag or something? Excuse my naive question I'm not familiar with python...

    fileName = data[6]
    if data[6][0] == '.':
        fileName = data[5]   data[6]
        if not (curIP == data[0] and curDate == data[1] and curAccession == data[5] and curExtention == data[6]):
            print('%s\t%s' % (data[0]   ","   fileName, data[1]))
    else:
        if not (curIP == data[0] and curDate == data[1] and curExtention == data[6]):
            print('%s\t%s' % (data[0]   ","   fileName, data[1]))

CodePudding user response:

I might do it like:

fileName = data[6]
match = (curIP, curDate, curExtension) == (data[0], data[1], data[6])
if fileName[0] == '.':
    fileName = data[5]   data[6]
    match &= curAccession == data[5]
if not match:
    print(f"{data[0]},{fileName}\t{data[1]}")

Another approach to keeping track of all the different pieces of data that need to match:

fileName = data[6]
matches = [(curIP, data[0]), (curDate, data[1]), (curExtension, data[6])]
if fileName[0] == '.':
    fileName = data[5]   data[6]
    matches.append((curAccession, data[5]))
if not all(a == b for a, b in matches):
    print(f"{data[0]},{fileName}\t{data[1]}")

CodePudding user response:

condition = curIP == data[0] and curDate == data[1] and curExtention == data[6]
if data[6][0] == '.':
    fileName = data[5]   data[6]
    if curAccession != data[5]:
        condition = False
if not condition:
    print('%s\t%s' % (data[0]   ","   fileName, data[1]))

The same, but much cleaner, as for me.

  • Related