Having a list:
x=['s',2,'3',4,5,6]
I can print it like this:
for i in x:
print i
However, as I've found out, it's a bit faster to just use one print statement, like this (below is how I got to this point):
print "\n".join( i.__class__==string and i or str(i) for i in x )
Given that I want to use the second option and that I would like the output to be something like (I would also like to include a counter):
v1: s v2: 2 v3: 3 etc
Here is what I've tried:
1)
count=0
print (("v"+str(++count)).join(":%s "% i for i in x ) )
result is::s, v0:2, v0:3, v0:4, v0:5, v0:6,
Really not what I'm aiming for.
a) str(++count) prints nothing, count++ gives synthax error
b) first v
is nowhere to be found, since join
in this case adds separators and there is no need for the first element
2)
print ( ["v"+str(++count)+ ":%s, "% i for i in x ] )
Gives ['v0:s, ', 'v0:2, ', 'v0:3, ', 'v0:4, ', 'v0:5, ', 'v0:6, ']
Better, but still no counter
and I don't want the []
being shown
3) Scratch all and restart:
print ",".join(i for i in x )
cannot concatenate string
and int
so it becomes:
print ",".join(i.__class__==string and i or str(i) for i in x )
which gives:
s,2,3,4,5,6
And here is where I'm stuck.
I would suggest to use
enumerate
:While I agree with @ARodas's answer, I'd like to also point out that:
You need to make sure printing is really a bottleneck in your program before starting to optimize it (it very rarely is).
expr1 and expr2 or expr3
was used prior to Python 2.5, whenexpr2 if expr1 else expr3
ternary operator was introduced. If you do not target Py <= 2.4,if else
is preferable.Instead of
i.__class__==string
it is better to writeisinstance(i, string)
(what isstring
, anyway? Did you meanstr
?).Moreover, you do not really need to check that:
str()
of a string just returns this string.There is no
++
operator in Python.++count == +(+count) == count
.