0

I have tried multiple ways to convert this, but all were unsuccessful. For example, my list is.

testscores= [['John', '99', '87'], ['Tyler', '43', '64'], ['Billy', '74', '64']]

I want to convert only the numbers to intergers because I will eventually average the actual scores later on and leave the names in a string.

I want my result to look like

testscores = [['John', 99, 87], ['Tyler', 43, 64], ['Billy', 74, 64]]

I've tried numerous for loops to try and only int the numbers in these lists but none have worked at all. If any of you need some of my test code, I can add. Thanks.

4
  • Are all the internal lists of the same size of 3? Commented Apr 20, 2013 at 19:21
  • No, not necessarily. I'm hoping to get the code to work no matter now many internal lists I have, in case there are additional students to add later on. Commented Apr 20, 2013 at 19:23
  • I mean, not the number of the lists, but their own length, is that always like [name, score1, score2]? Commented Apr 20, 2013 at 19:24
  • But yes, each internal list only has 3 elements inside of it. The number of internal lists can change however. Commented Apr 20, 2013 at 19:24

3 Answers 3

2

In case if all the nested lists have length 3 (i.e. 2 scores per student), that's as simple as:

result = [[name, int(s1), int(s2)] for name, s1, s2 in testscores]
Sign up to request clarification or add additional context in comments.

Comments

2

In Python 2, for arbitrary length of sublists:

In [1]: testscores = [['John', '99', '87'], ['Tyler', '43', '64'],
   ...: ['Billy', '74', '64']]

In [2]: [[l[0]] + map(int, l[1:]) for l in testscores]
Out[2]: [['John', 99, 87], ['Tyler', 43, 64], ['Billy', 74, 64]]

In Python 3 (or 2):

In [2]: [[l[0]] + [int(x) for x in l[1:]] for l in testscores]
Out[2]: [['John', 99, 87], ['Tyler', 43, 64], ['Billy', 74, 64]]

Comments

0

There have been a few solutions posted already, but here's my try at this, without relying on try and except.

newScores = []
for personData in testScores:
    newScores.append([])
    for score in personData:
        if score.isdigit(): # assuming all of the scores are ints, and non-negative
            score = int(score)
        elif score[:1] == '-' and score[1:].isdigit(): # using colons to prevent index errors, this checks for negative ints for good measure
            score = int(score)
    newScores[-1].append(score)
testscores = newScores

On a side note, I suggest that you consider using the Python dict structure, which allows you to do something like this:

testScores = {} # or = dict()
testScores["John"] = [99,87]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.