acoustic python
acoustic python

Reputation: 279

How to covert this list of strings into integers

I have a list which consists of a list of string, I am interested in converting this list into an int. How to do this.

k2=["'95', '66', '137', '70', '20'", "'36', '66', '44', '214', '105', '133'"]
    k3=[]
    for i in range(len(k2)):
      k3[i]=int(k2[i])

Upvotes: 1

Views: 100

Answers (5)

R. Marolahy
R. Marolahy

Reputation: 1586

One liner solution:

k3 = [int(i) for i in ','.join([_k2.replace("'", "").replace(" ", "") for _k2 in k2]).strip().split(',')]

Upvotes: 0

Epsi95
Epsi95

Reputation: 9047

for more generic case, you can use regular expression

import re

out = []

k3=["'95', '66', '137', '70', '20'", "'36', '66', '44', '214', '105', '133'"]

for i in k3:
    result = re.findall(r'\D(\d+)\D', i)
    out.extend(result)
    
print(out)
['95', '66', '137', '70', '20', '36', '66', '44', '214', '105', '133']

regex explanation:

https://regex101.com/r/2rhNJl/1

Upvotes: 1

ThePyGuy
ThePyGuy

Reputation: 18416

Iterate through each item in the list, then split them on , and strip off the preceding and following quote ' and white space

result = []
for v in k2:
    result += [int(i.strip("' ")) for i in v.split(',')]

#output:
[95, 66, 137, 70, 20, 36, 66, 44, 214, 105, 133]

Upvotes: 1

Prayalankar Ashutosh
Prayalankar Ashutosh

Reputation: 181

In case you have to get the list of lists. Iterate over the list split on the , and find the ints and you can append the results at same index.

for i,va in enumerate(k3):
    k3[i] = ([int(re.findall(r'\d+', val)[0]) for val in va.split(',')])
# output[[95, 66, 137, 70, 20], [36, 66, 44, 214, 105, 133]]

Upvotes: 0

user15512272
user15512272

Reputation:

This can be done with a single list comprehension.

In [28]: k3 = [int(string.strip(" '")) for k in k2 for string in k.split(',')]
Out[29]: [95, 66, 137, 70, 20, 36, 66, 44, 214, 105, 133]

Upvotes: 0

Related Questions