robert williams robert williams - 1 year ago 97
Python Question

if-else in python list comprehensions

is it possible to write list comprehensions for the following python code:

for str in range(0,len(mixed_content)):
if (mixed_content[str].isdigit()):

can we use else block in list comprehensions ? I tried to write list comprehensions for above code :

num_list , string_list = [ mixed_content[str] for str in range(0,len(mixed_content)) if(mixed_content[str].isdigit()) else ]

Answer Source

You can only construct one list at a time with list comprehension. You'll want something like:

nums = [foo for foo in mixed_list if foo.isdigit()]
strings = [foo for foo in mixed_list if not foo.isdigit()]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download