Home > OS >  Removing apostrophes in list
Removing apostrophes in list

Time:08-12

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'

CodePudding user response:

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]

CodePudding user response:

You can use list comprehensions with map on every sub list

x = [list(map(float, y)) for y in x]

CodePudding user response:

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)]

CodePudding user response:

Try this :

import json
new_list= json.loads(str(x).replace('\'',''))
list2 = []

for i in new_list:
    list2.append(tuple(i))

print(list2)

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)]

To convert these values to integer :

for i in list2:
    for j in i:
        print(int(j))
  • Related