【问题标题】:How can I convert list of list with strings to list of list with ints in python?如何在python中将带有字符串的列表列表转换为带有整数的列表列表?
【发布时间】:2013-04-21 03:52:30
【问题描述】:

我尝试了多种方法来转换它,但都没有成功。 比如我的清单是。

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

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

我希望我的结果看起来像

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

我尝试了很多 for 循环来尝试,并且只尝试 int 这些列表中的数字,但根本没有任何效果。如果你们中的任何人需要我的一些测试代码,我可以添加。 谢谢。

【问题讨论】:

  • 是不是所有的内部列表都是一样大小的3?
  • 不,不一定。无论我现在有多少内部列表,我都希望代码能够正常工作,以防以后有其他学生要添加。
  • 我的意思是,不是列表的数量,而是它们自己的长度,是不是总是像[name, score1, score2]
  • 但是是的,每个内部列表里面只有 3 个元素。但是,内部列表的数量可能会发生变化。

标签: python list


【解决方案1】:

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

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

【讨论】:

    【解决方案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]]
    

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-06-14
        • 2021-08-21
        • 1970-01-01
        • 2020-07-30
        • 2021-03-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多