0

If I have an array that contains only strings, but some of them are numbers, how would I search through the array, determine which strings are actually numbers, and add those numbers to a new array? An example of the array is as follows: [ "Chris" , "90" , "Dave" , "76" ]

I have tried using a for loop to consecutively use isdigit() on each index, and if it is true to add that item to the new array.

scores = []
    for i in range(len(name_and_score_split)):
        if name_and_score_split[i].isdigit() == True:
            scores.append(name_and_score_split[i])

When the above code is ran it tells me list data type does not have the "isdigit" function edit: iv'e found that my problem is the list is actually a list of lists.

lumi90
  • 1
  • 2
  • what exactly is the problem? your code does that currently, are you asking if this is the proper way to do it? – gold_cy Mar 27 '19 at 02:44

3 Answers3

2

Use a list-comprehension and also utilise the for-each property of Python for rather than iterating over indices:

lst = ["Chris" , "90" , "Dave" , "76"]

scores = [x for x in lst if x.isdigit()]
# ['90', '76']

Alternately, filter your list:

scores = list(filter(lambda x: x.isdigit(), lst))
Austin
  • 25,759
  • 4
  • 25
  • 48
0

Assuming what you're trying if for integers you can do something like:

// Taken from and changing float by int.

def is_number(s):
    try:
        int(s)
        return True
    except ValueError:
        return False

Then you can do

[x for x in name_and_score_split if is_number(x)]
dcg
  • 4,187
  • 1
  • 18
  • 32
0

If you want list of int:

s = ["Chris", "90", "Dave", "76"]
e = [int(i) for i in s if i.isdigit()]
print(e)
# OUTPUT: [90, 76]
Camile
  • 107
  • 5