2

I have this data

[[ 2.696000e+00  0.000000e+00  0.000000e+00  0.000000e+00]
 [ 2.577000e+00  0.000000e+00  0.000000e+00  0.000000e+00]
 [ 0.000000e+00 -2.560096e+03  0.000000e+00  0.000000e+00]
...

and want to print it as such, for each row

2.696000e+00 & 0.000000e+00 & 0.000000e+00 & 0.000000e+00 //
2.577000e+00 & 0.000000e+00 & 0.000000e+00 & 0.000000e+00 //
...

I have done is

for k in range(1):
for i in range(len(data[k])):
    print(data[k][i],'&')
    if i == len(data[k])-1:
        print(data[k][i],'//')

Which outputs

2.696 &
0.0 &
0.0 &
0.0 &
0.0 //

How to get rid of the new line between each entry of the row?

Barmar
  • 741,623
  • 53
  • 500
  • 612
Lyu
  • 133
  • 5
  • ``print(data[1][i],'&', end= " ")`` And you dont need ``for k in range(1):`` just replace ``k`` with zero in every line – Psytho Jul 05 '23 at 19:19
  • Does this answer your question? [How to print without a newline or space](https://stackoverflow.com/questions/493386/how-to-print-without-a-newline-or-space) – Psytho Jul 05 '23 at 19:20

2 Answers2

5

You can use str.join to join the numbers by & and then print // as last string:

data = [
    [2.696000e00, 0.000000e00, 0.000000e00, 0.000000e00],
    [2.577000e00, 0.000000e00, 0.000000e00, 0.000000e00],
    [0.000000e00, -2.560096e03, 0.000000e00, 0.000000e00],
]

for row in data:
    print(' & '.join(map(str, row)), '//')

Prints:

2.696 & 0.0 & 0.0 & 0.0 //
2.577 & 0.0 & 0.0 & 0.0 //
0.0 & -2560.096 & 0.0 & 0.0 //
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
1

Just use the join functions

' & '.join(map(lambda s: '%E'%s, [2.696000e00, 0.000000e00, 0.000000e00, 0.000000e00]))

Outputs

'2.696000E+00 & 0.000000E+00 & 0.000000E+00 & 0.000000E+00'

With the above approach, you can just do one loop and convert the array into a string with your preferred join character.

The map function is required to convert the decimal values to string. The lambda fn just formats the decimal into string using the E notation. A 'str' mapping would get rid of the 0s. See this for details.

If you just want to stop print from spitting out newline, check this

Edit1: Updated code with map example

Muhammad Ali
  • 712
  • 7
  • 14