Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Coverting a list of strings into tuples using a function in python

I’m relatively new to Python and just got introduced to functions. I’m working on an example for university and don’t quite understand how to write the needed function.

We are provided with a list of strings:

lines = ['1: 362.5815 162.5823\n', '2: 154.1328 354.1330\n', '3: 168.9325 368.9331\n',.. etc (there are 100 keys)

Using my first function I have to convert this list into tuples conatining the values as a list.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I know how to convert it for the first item of the list:

f1 = lines[0].split(" ")

f1tuple = tuple(f1)

f1tuple2 = (f1tuple[0], [float(f1tuple[1]), float(f1tuple[2])])

But I don’t understand how to write a function for the next 100 items.

Would really appreciate some help.

>Solution :

With a ‘for’ loop you can run over all items in a list:

all_tuples = [] #<-- create a list to put all you tuples into
for value in lines: #<-- for loop, running through all values in you lines list
    f1 = value.split(" ") #<-- your code1
    f1tuple = tuple(f1) #<-- your code2
    f1tuple2 = (f1tuple[0], [float(f1tuple[1]), float(f1tuple[2])]) #<-- your code3
    all_tuples.append(f1tuple2) #<-- Adding the tuple to the list
all_tuples
[('1:', [362.5815, 162.5823]),
 ('2:', [154.1328, 354.133]),
 ('3:', [168.9325, 368.9331])]

As a function:

def get_all_tuples(lines): #<-- create a function
    all_tuples = []
    for value in lines:
        f1 = value.split(" ")
        f1tuple = tuple(f1)
        f1tuple2 = (f1tuple[0], [float(f1tuple[1]), float(f1tuple[2])])
        all_tuples.append(f1tuple2)
    return all_tuples #<-- return your all_tuples list
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading