0

I am converting a user input list of strings into tuples. The user inputs a list of fractions ie: (Please no "import fractions" suggestions)

fractions = ["1/2","3/5","4/3","3/8","1/9","4/7"]

I normally would use the following code that works:

user_input = 0
list_frac = []
print('Enter fractions into a list until you type "stop" in lower case:')
while user_input != 'stop':
    user_input = input('Enter a fraction ie: "1/2" >>>')
    list_frac.append(user_input)
list_frac.pop()   # pop "stop" off the list

result = []
for i in list_frac:
    result.append(tuple(i.split('/')))
print(result)

The result is a list of tuples:

fractions = [('1','2'),('3','5')('4','3'),('3','8'),('1','9'),('4','7')]

I want to change the values in the tuples to integers as well and I dont know how

However I also wish to learn lambda functions so I am practicing on simple code like this. This is my attempt at the same code using lambda function syntax:

tup_result = tuple(map(lambda i: result.append(i.split('/')), result))

But the result is an empty list and no error codes to help me.

The Question: How to change the strings in the list of tuples to ints, and then accomplish all this with the lambda function one liner.

Any suggestions, I have the general concept pf a lambda function down but actually implementing this is a little confusing, thanks for the help folks!

1 Answer 1

1

I used comprehensitions to solve the task:

fractions = ["1/2","3/5","4/3","3/8","1/9","4/7"]
print([(int(x),int(y)) for  (x,y) in [k.split('/') for k in fractions]])
>>>[(1, 2), (3, 5), (4, 3), (3, 8), (1, 9), (4, 7)]

I started with python not long time ago myself and was confused how to use lambda in the beginning as well. Then I read, that Guido van Rossum had suggested, that lambda forms would disappear in Python3.0 AlternateLambdaSyntax, since then I have not used lambda at all and have no problem with the issue at all. You have to understand how it works when you see it in some code, but you can almost always can write more readable code without using lambda (though I can be wrong). I hope, it helped.

Update

there is a solution solution with map() and lambda, though I would not wish to see it in my code on my worst enemy:

print([(int(x),int(y)) for  [x,y] in list(map(lambda frac: frac.split('/'),fractions))])
>>>[(1, 2), (3, 5), (4, 3), (3, 8), (1, 9), (4, 7)]
Sign up to request clarification or add additional context in comments.

1 Comment

I need to figure out how to do this using map() however.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.