Home > OS >  Convert list elements to tuples
Convert list elements to tuples

Time:10-25

I'm trying to convert a list of elements to tuples and then add the tuples to a new list but keep running into issues with how the results are presented.

My list is:

list = ['(One, 1)', '(Two, 2)', '(Three, 3)', '(Four, 4)']

When I try to convert it to a tuple using:

for a in list1:
    list2.append(tuple([a.replace("(", "").replace(")", "")]))

It gives the output:

print(list2)
[('One, 1',), ('Two, 2',), ('Three, 3',), ('Four, 4',)]

I want it to give the following output:

[('One', 1), ('Two', 2), ('Three', 3), ('Four', 4)]

How would I go about doing this?

CodePudding user response:

list1 = ['(One, 1)', '(Two, 2)', '(Three, 3)', '(Four, 4)']
list2 = []

for a in list1:
    str = a.replace("(", "").replace(")", "").split(",")
    list2.append((str[0], int(str[1])))
    
print(list2)

Output:

[('One', 1), ('Two', 2), ('Three', 3), ('Four', 4)]

CodePudding user response:

a.replace("(", "").replace(")", "")

Well, yes. All you are doing here, is removing some chars (parenthesis, but those are just chars in this context) from a string. So, on each string "(One, 1)" you apply a conversion to get a string "One, 1".

Then, you put that string in a list

[a.replace("(", "").replace(")", "")]

So, what you get is just the list containing that string: ["One, 1"]

That you convert into a tuple

tuple([a.replace("(", "").replace(")", "")])

So ("One, 1",) instead of ["One, 1"]. Just a tuple containing a single string.

Apparently, what you wanted was to split that string into substring, because of the coma.

a.replace("(", "").replace(")", "").split(',')

To get a list ['One', ' 1']. And then transform this into a tuple, and append it

tuple(a.replace("(", "").replace(")", "").split(','))

('One', ' 1')

So, altogether

[tuple(a.replace("(", "").replace(")", "").split(',')) for a in list1]

Your "wanted" result shows that, in addition, you want to parse the second part of each tuple to get an int

So

for a in list1:
    x,y=a.replace("(", "").replace(")", "").split(' ')
    list2.append((x, int(y)))

Note, that there is no more "tuple" here, because it is explicitly created from x and y, that I had to explicitly name, to be able to convert one of them

Also note that I did not need to strip the space you probably noticed in that second part of the tuple, because conversion to int took care of it. Ortherwise, you would have needed a more complex split, (or an explicit strip) to ensure that there is no spaces included in the two parts)

Last note: avoid naming variables "list" (or, "str" for that matter :)). Those are predefined symbols. You can overwrite them, sure, since they are not keywords, but, you are not supposed to. They are pretty important part of the language, and strange things may happen in your code if you change the meaning of "list" or "str".

CodePudding user response:

I'd recommend to use reg exp here instead of eval, literal_eval or .replace(). In my opinion using reg exp here is much more flexible than using .replace() method which should be duplicated in the code a couple of times (that brings "code smells" to your code). Also I do not recommend to use eval() since it's not secure. Also, it's not necessary to use loops here to iterate over initial list elements and do some work, because we have map() which does almost the same but faster (in the meaning of performance).

import re

my_initial_list = ['(One, 1)', '(Two, 2)', '(Three, 3)', '(Four, 4)']

PATTERN = r"\((\w ), (\d )\)"
PATTERN_C = re.compile(PATTERN)


def parse_string_element(string_element, pattern=PATTERN_C):
    parsed_elem = re.findall(pattern, string_element)[0]
    return parsed_elem[0], int(parsed_elem[1])


my_final_list = list(map(parse_string_element, my_initial_list))

print(my_final_list)

# [('One', 1), ('Two', 2), ('Three', 3), ('Four', 4)]
  • Related