Home > OS >  Is there a way to set conditions for end parameter in python?
Is there a way to set conditions for end parameter in python?

Time:07-18

I'm new to programming, just going through a wee online course, but I've hit a stumbling block on one of the tasks.

The task is to print the coordinates in the format of an 8 by 8 grid. So A1 to H1 is on the first line, A2 to H2 on the second, etc. The task is to be done using nested list comprehension where possible.

So far I have this, which puts all coordinates on the same line separated by a space:

let=["A","B","C","D","E","F","G","H"]
num=[1,2,3,4,5,6,7,8]

[print(i,j,sep="",end=" ") for j in num for i in let]

I've tried some daft things that definitely do not work, such as:

let=["A","B","C","D","E","F","G","H"]
num=[1,2,3,4,5,6,7,8]

[print(i,j,sep="",end=" " if i!=H) for j in num for i in let]

Is there a way to do this in a single line without typing out full "for" loops?

CodePudding user response:

try

let=["A","B","C","D","E","F","G","H"]
num=[1,2,3,4,5,6,7,8]

[print(i,j,sep="",end=" ") if i!='H' else print(end='') for j in num for i in let]

but as the comment said, try using loop instead when you want to print things

CodePudding user response:

I think there is no way to do this in one line because it will print all the coordinates in one line, so you will need extra lines to arrange them in a grid but you can use this code :

let=["A","B","C","D","E","F","G","H"]
num=[1,2,3,4,5,6,7,8]

for i in num:
    x=""
    for k in let:
        x =k str(i) " "
    print(x)

CodePudding user response:

I think some compromises need to be taken... single line "print comprehension"... is quite unpythonic. The main problem to your question, to impose conditions on print parameters, is a bit hard because the parameters are not callables.... Here just some examples of usage.

Construct a single string with \n and without optional print parameters.

let=["A","B","C","D","E","F","G","H"]
num=[1,2,3,4,5,6,7,8]

# for layout
col_sep, coords_sep = ' ', ''

print('\n'.join(col_sep.join(f'{i}{coords_sep}{j}' for i in let) for j in num))

Construct a list of strings, with optional print parameters

lst = [col_sep.join(f'{i}{coords_sep}{j}' for i in let) for j in num]
print(*lst, sep='\n')

With conditions on print parameters

The result should be properly design to make use of a "conditional" end parameter: construct out of the two given lists a flat list and then use modulo-arithmetic:

lst = ' '.join(col_sep.join(f'{i}{j}' for i in let) for j in num).split()
[print(term, end=(lambda x: ' ' if i % len(num) else '\n')(i)) for i, term in enumerate(lst, 1)]

lambda-part can be also replaced with end=' ' if i % len(num) else '\n'

  • Related