質問

I am trying to implement a ternary conditional operator in a list-comprehension. I have written it like this:

lst.append(dict2obj(item)) if type(item) is not in ['int'] else lst.append(item) for item in v

Where lst is empty list and v is another list with various elements. Editor is showing it syntactically incorrect. What am I doing wrong?

役に立ちましたか?

解決

  • If you mean to write list comprehension you missed [, ]:
  • There is no is not in operator. Use not in.
  • type function does not return string. Why not use isinstance(item, int)?

[lst.append(dict2obj(item)) if not isinstance(item, int) else lst.append(item)
 for item in v]

Use simple for loop if possible. It's more readable.

for item in v:
    if not isinstance(item, int)
        lst.append(dict2obj(item))
    else:
        lst.append(item)

他のヒント

If the lst is empty from the start, you can simply create it like this:

lst = [dict2obj(item) if not isinstance(item, int) else item for item in v]

If you already have the list and want to add items, the proper way to do this in Python is to just extend the list you have with the new list:

lst.extend([dict2obj(item) if not isinstance(item, int) else item for item in v])

Or something like this (this uses an generator) to prevent extra overhead:

map(lst.append, (dict2obj(item) if not isinstance(item, int) else item for item in v))

I avoid mixing list comprehensions with ternary operators because it's too hard to understand what the function does at a glance.

I also try to use list comprehensions only for building up a list of return values. If I desire side-effects (such as adding items to a list), I will do this in a regular for-loop. This is especially true when I don't care about the list of return values. If you do go the route of a list comprehension, use the consume recipe for itertools (http://docs.python.org/2/library/itertools.html#recipes). consume((lst.append(dict2obj(item)) if not isinstance(item) else lst.append(item) for item in v), None)

Here's how I'd solve this problem if I didn't do use @falsetru's approach (which is probably the easiest to read)

def convert(item):
    if not isinstance(item, int):
        result = dict2obj(item)
    else:
        result = item
    return result

lst.extend(map(convert, v)) #or itertools.imap

convert could be a lambda function if you're willing to trade compactness for readability.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top