繁体   English   中英

如何在python中将带有字符串的列表列表转换为带有int的列表列表?

[英]How can I convert list of list with strings to list of list with ints in python?

我尝试了多种方法将其转换,但均未成功。 例如,我的清单是。

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

我只想将数字转换为整数,因为最终我将对实际分数进行平均,然后将名称保留在字符串中。

我希望我的结果看起来像

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

我已经尝试了许多for循环,并且只将这些列表中的数字进行了整整,但是根本没有任何作用。 如果您需要我的一些测试代码,我可以添加。 谢谢。

如果所有嵌套列表的长度为3(即每个学生2个分数),则很简单:

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

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

已经发布了一些解决方案,但是这是我的尝试,不依赖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]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM