-1

I have a list as above:

probs= ['2','3','5','6']

and i want to convert those string to a numeric values like the following result:

resultat=[2, 3, 4, 5, 6]

I tried some solutions appearing on this link: How to convert strings into integers in Python? such as this one:

new_list = list(list(int(a) for a in b) for b in probs if a.isdigit())

but it didn't work, someone can help me to adapt this function on my data structure, i will be really thankful.

Community
  • 1
  • 1
Ha KiM's
  • 119
  • 1
  • 1
  • 13
  • `resultat = [int(item) for item in probs]`? – mgilson Jul 15 '16 at 19:03
  • Just a problem with syntax. You are creating a list of lists. Instead, use: `new_list = list(int(a) for a in probs if a.isdigit())` – user1952500 Jul 15 '16 at 19:07
  • "but it didn't work, someone can help me to adapt this function on my data structure" - the structure is *simpler* than the one in the other question. Solving programming problems requires *understanding*, not just blind adaptation of existing code to the circumstances. – Karl Knechtel May 18 '23 at 22:01

3 Answers3

4

Use int() and list comprehension iterate the list and convert the string values to integers.

>>> probs= ['2','3','5','6']
>>> num_probs = [int(x) for x in probs if x.isdigit()]
>>> num_probs
[2, 3, 5, 6]
Haifeng Zhang
  • 30,077
  • 19
  • 81
  • 125
2

if your list is as above, you don't need to check if the value is a number. something like

probs = ["3","4","4"];
resultat = [];

for x in probs:
    resultat.append(int(x))

print resultat

would work

  • Thank you @Idco0 for the answer. but i receive the following error: File " stdin", lin 2 resultat.append(int(x)) IdentationError: expected an indented block – Ha KiM's Jul 15 '16 at 19:22
0
>>> probs= ['2','3','5','6']
>>> probs= map(int, probs)
>>> probs
[2, 3, 5, 6]

or (as commented):

>>> probs= ['2','3','5','6']
>>> probs = [int(e) for e in probs]
>>> probs
[2, 3, 5, 6]
>>> 
Billal Begueradj
  • 20,717
  • 43
  • 112
  • 130
  • Thank you @Billal for the answer. but i receive the following error: ValueError:invalid literal for int() with base 10: '0.00390625' – Ha KiM's Jul 15 '16 at 19:24
  • 1
    it must change int () on float() and it works really good. I appreciate it – Ha KiM's Jul 15 '16 at 19:29