如何将带有字符串的列表列表转换为带有inby的列表列表?

时间:2013-04-20 19:20:10

标签: python list

我尝试了多种方法来转换它,但都没有成功。 例如,我的列表是。

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

我想只将数字转换为整数,因为我最终会将实际分数平均化,并将名字保留在字符串中。

我希望我的结果看起来像

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

我已经尝试了很多for循环来尝试并且只对这些列表中的数字进行int,但是根本没有。如果您需要我的一些测试代码,我可以添加。 感谢。

3 个答案:

答案 0 :(得分:2)

如果所有嵌套列表的长度都为3(即每位学生2分),那就简单如下:

result = [[name, int(s1), int(s2)] for name, s1, s2 in testscores]

答案 1 :(得分:2)

在Python 2中,对于任意长度的子列表:

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

在Python 3(或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]]

答案 2 :(得分:0)

已经发布了一些解决方案,但这是我的尝试,而不依赖于tryexcept

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

另外,我建议您考虑使用Python dict结构,它允许您执行以下操作:

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