Python list printing (formatting)

2020-07-23 09:21发布

问题:

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.

回答1:

I would suggest to use enumerate:

x = ['s',2,'3',4,5,6]
print ', '.join('v{}: {}'.format(v, i) for v, i in enumerate(x))
# v0: s, v1: 2, v2: 3, v3: 4, v4: 5, v5: 6


回答2:

While I agree with @ARodas's answer, I'd like to also point out that:

  1. You need to make sure printing is really a bottleneck in your program before starting to optimize it (it very rarely is).

  2. expr1 and expr2 or expr3 was used prior to Python 2.5, when expr2 if expr1 else expr3 ternary operator was introduced. If you do not target Py <= 2.4, if else is preferable.

  3. Instead of i.__class__==string it is better to write isinstance(i, string) (what is string, anyway? Did you mean str?).

  4. Moreover, you do not really need to check that: str() of a string just returns this string.

  5. There is no ++ operator in Python. ++count == +(+count) == count.



标签: python-2.7