Unsupported operand types in if/else list comprehension
gallium.arsenide at gmail.com
Fri Apr 10 23:18:53 CEST 2009
On Apr 10, 5:07 pm, Mike H <cmh.pyt... at gmail.com> wrote:
> From playing around with other examples, I get the feeling
> that Python is calculating both values (inst and '"'+inst+'"')
> before selecting which one to pass to the new list. Am I right?
I believe so. (I'm sure the experts here will tell you more
> Is there any way I can do this using list comprehension?
Yes. If you are using 2.5 or later, you can do this:
Python 2.6.1 (r261:67517, Dec 4 2008, 16:51:00) [MSC v.1500 32 bit
Type "help", "copyright", "credits" or "license" for more information.
>>> b=[(x if not isinstance(x, str) else '"'+x+'"') for x in a]
['"test"', 1, '"two"']
If you are trying to make a CSV file, then even better may be to use
the csv module.
More information about the Python-list