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.
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