Home > OS >  Coverting a list of strings into tuples using a function in python
Coverting a list of strings into tuples using a function in python

Time:11-24

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

The input to the function is a list of strings in the following format:

lines = ['1: 362.5815 162.5823\n', 
'2: 154.1328 354.1330\n', 
'3: 168.9325 368.9331\n',.. ]

I have to create a function that converts each item in the list into a tuple and store the output in a new list.

To convert a single item of the list into a tuple, I am using the following code:

```python
f1 = lines[0].split(" ")
f1tuple1 = tuple(f1)
f1tuple2 = (f1tuple[0], [float(f1tuple[1]), float(f1tuple[2])])
How do I perform the same action for all of the items in the list?
I would really appreciate help in this matter.

CodePudding user response:

Edit: as rightfully pointed out in the comments, no need to use map.

I updated with use of a function and correct types (first tuple element as int):

lines = ['1: 362.5815 162.5823\n', '2: 154.1328 354.1330\n', '3: 168.9325 368.9331\n']

def create_tuples(lines):
    return [(int((y := x.split(" "))[0].strip(':')),
             [float(y[1]), float(y[2].strip('\n'))]
            ) for x in lines]

print(create_tuples(lines))

Output:

[(1, [362.5815, 162.5823]), (2, [154.1328, 354.133]), (3, [168.9325, 368.9331])]

Note: the assignment in the list comprehension only works for python >= 3.8

Old answer:

You can use map:

fituples = list(map(lambda x: tuple(x.strip("\n").split(" ")), lines))

Output:

[('1:', '362.5815', '162.5823'), ('2:', '154.1328', '354.1330'), ('3:', '168.9325', '368.9331')]

CodePudding user response:

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

CodePudding user response:

def items(lines):
   vals = [x.split(" ") for x in lines]
   return [(i[0], i[1], i[2]) for i in vals]

CodePudding user response:

Using re :

tuples = []
for item in lines:
    if m := re.match(r"(\d ):\s (\S )\s (\S )", item):
        tuples.append([m.group(1), (m.group(2), m.group(3))])
  • Related