Removing apostrophes in list

Question:

how to remove apostrophes in list like below:

x = [['3.937', '1.968', '1.968'], ['3.937', '1.968', '1.968'], ['3.937', '1.968', '1.968'], ['7.874', '3.937', '1.968'], ['7.874', '3.937', '1.968'], ['7.874', '3.937', '1.968'], ['7.874', '3.937', '1.968'], ['7.874', '3.937', '1.968'], ['7.874', '3.937', '1.968']]

All in all i want to convert this thing to like this:

x = [(3.937,1.968,1.968),(3.937,1.968,1.968)]

result = int(my_list[0])

but there is errors like :
result = int(x[0])
Traceback (most recent call last):

result = int(x[0])
TypeError: int() argument must be a string, a bytes-like object or a real number, not 'list'
Asked By: LogicLover90

||

Answers:

This is a nested list. If you use int(x[0]) you are accessing the first sublist: ['3.937','1.968','1.968'] which can’t be transformed via int(), therefore you need to use a nested list-comprehension approach:

result = [[float(value) for value in sublist] for sublist in x]

If you’d like to have tuples instead of nested-list, you can use:

result = [tuple([float(value) for value in sublist]) for sublist in x]
Answered By: Celius Stingher

You can use list comprehensions with map on every sub list

x = [list(map(float, y)) for y in x]
Answered By: Guy

The apostrophes show that the values are strings. Each string seems to be a representation of a float. Therefore:

x = [['3.937', '1.968', '1.968'], ['3.937', '1.968', '1.968'], ['3.937', '1.968', '1.968'], ['7.874', '3.937', '1.968'], ['7.874', '3.937', '1.968'], ['7.874', '3.937', '1.968'], ['7.874', '3.937', '1.968'], ['7.874', '3.937', '1.968'], ['7.874', '3.937', '1.968']]

x = [tuple(map(float, e)) for e in x]

print(x)

Output:

[(3.937, 1.968, 1.968), (3.937, 1.968, 1.968), (3.937, 1.968, 1.968), (7.874, 3.937, 1.968), (7.874, 3.937, 1.968), (7.874, 3.937, 1.968), (7.874, 3.937, 1.968), (7.874, 3.937, 1.968), (7.874, 3.937, 1.968)]
Answered By: Stuart
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.