Py list comprehension

Hi guys,

print (lon, lat)

(Array[float]((0.41731154841721158, 0.91070678515577241)), Array[float]((0.061722582332493753, 0.23535268598005044, 0.32541661444908748, 0.51119481806677869, 0.62225194327164557, 0.70637337819991963)))

print [ j for j in [ i for i in ( lon, lat ) ] ]

(Array[float]((0.41731154841721158, 0.91070678515577241)), Array[float]((0.061722582332493753, 0.23535268598005044, 0.32541661444908748, 0.51119481806677869, 0.62225194327164557, 0.70637337819991963)))

for i in (lon, lat):
for j in i:
print j

0.0617225823325
0.910706785156
0.417311548417
ecc ecc

ultimate result would be what i should get,
why with the list comprehension
I don’t get the same result
of nested for loops?

Hello,
what happens if you try

[print j for j in [ i for i in ( lon, lat ) ] ]

With the list comprehension you are printing the whole list whereas in the nested loop you are repeatedly printing single values.

@Dancergraham, Thanks for the reply, I tried your syntax but I get an error.

perhaps the only solution is this:

for w in [ j for i in (lon, lat) for j in i ]: print w

on the net I found the correct syntax for the double comprehension list (reverse the sequence of for loops)

1 Like

or print "\n".join(map(str, (lon + lat)))

Explanation : concatenate the two lists by adding them together, apply the string function to turn them into strings and then print them with newline characters in between

1 Like

Hi @Dancergraham, I like this method used to do the printing. i tried to use the separator “\ n” but i didn’t know the function of the map. thanks for your posted example :+1:

Hi, it would be possible to add an enumerate type counter “for e,i in enumerate(range(10)):”

using print "\n".join(map(str, (lon + lat))) to get a result like this:

( Nested 1: Array[float]((0.41731154841721158, 0.91070678515577241)), Nested 2: Array[float]((0.061722582332493753, 0.23535268598005044, 0.32541661444908748, 0.51119481806677869, 0.62225194327164557, 0.70637337819991963)))

thanks

a = [1,2,3]
b = [4,5,6]
c = [7,8,9]

z = [a,b,c]

print “\n”.join(map(str,[“Group”+str(e[0])+str(“\n”)+str(z[e[0]]) for e in enumerate(range(len(z)))]))

print:

Group0
[1, 2, 3]
Group1
[4, 5, 6]
Group2
[7, 8, 9]

a = [1,2,3]
b = [4,5,6]
c = [7,8,9]

z = [a,b,c]

print “\n”.join(map(str,[“Group”+str(e[0])+str(“\n”)+“\n”.join(map(str,(z[e[0]]))) for e in enumerate(range(len(z)))]))

output:

Group0
1
2
3
Group1
4
5
6
Group2
7
8
9