Unsupported operand types in if/else list comprehension
John Yeung
gallium.arsenide at gmail.com
Fri Apr 10 17:18:53 EDT 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
definitively.)
> 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
(Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> a=['test',1,'two']
>>> b=[(x if not isinstance(x, str) else '"'+x+'"') for x in a]
>>> b
['"test"', 1, '"two"']
>>>
If you are trying to make a CSV file, then even better may be to use
the csv module.
John
More information about the Python-list
mailing list