'Converting List Comprehensions to For Loops in Python, if/else
I have just started learning Python and would like to understand how to convert list comprehension to for loops together if if/elif/else statements.
Initial Question
Write a function, splitter that takes in an IC string, and outputs a tuple of the digits only. For example, if we do: a,b,c,d,e,f,g = splitter('S1234567D') a will store 1. b will store 2. ... g will store 7.
List Comprehension
Suggested Answer
def splitter(IC):
a,b,c,d,e,f,g = [i for i in IC if i.isnumeric()] return a,b,c,d,e,f,gTesting the definition
a,b,c,d,e,f,g = splitter('S1234567Z')
print(a,b,c,d,e,f,g)
#Output 1 2 3 4 5 6 7
Main Question
If there a way to convert the above list comprehension to for loop using if/elif/else?
I have tried some variations, but am unable to run the cell as a,b,c,d,e,f,g expects 7 arguments and assigning a,b,c,d,e,f,g with an empty list and using append does not seem to work.
def splitter(IC):
for i in IC[1:8]:
if i.isnumeric():
return a,b,c,d,e,f,g = splitter(IC)
else:
pass
Please help. Thank you!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
