【问题标题】:how to match python list using regular expression如何使用正则表达式匹配python列表
【发布时间】:2015-11-06 22:39:12
【问题描述】:

我在 python ["john","doe","1","90"]["prince","2","95"] 中有以下列表。第一个数字列是字段:id,第二个数字字段是分数。我想在 python 中使用re 来解析字段并打印。到目前为止,我只知道如何拆分字段逗号。有谁可以帮忙?

【问题讨论】:

  • 你尝试了吗?如果是请添加!
  • 没有逗号可以分割
  • I would like to use re in python to parse out the field and print - 究竟是什么迫使你使用import re并使用它?
  • 您的示例是字符串列表,而不是单个字符串。 re 用于在单个字符串中查找模式 - 所以不清楚你在问什么。

标签: python


【解决方案1】:

你最好使用字典而不是正则表达式(我在这里看不到你是如何使用的):

{'name': 'John Doe', 'id': '1', 'score': '90'}

或者更好的是,使用数字:

{'name': 'John Doe', 'id': 1, 'score': 90}

【讨论】:

    【解决方案2】:

    这里你真的不需要正则表达式。您可以只使用 isinstance() 和切片。

    这应该做你想做的:

    a_list = ['john','doe','1','90']
    
    for i, elem in enumerate(a_list):
        try:
            elem = int(elem)
        except ValueError, e:
            pass
        if isinstance(elem, int):
            names_part = a_list[:i-1]
            id_and_score = a_list[i-1:]
    
            print 'name(s): {0}, '.format(' '.join(names_part)), 'id: {id}, score: {score}'.format(id=id_and_score[0], score=id_and_score[1])
    

    不过,如果我们知道您的数据来源,或者如果有办法确定字段位置,您可以按照建议将您的列表转换为字典。如果您提取数据,您可能会考虑构建一个 dict 而不是一个列表,以防止您必须执行上述操作。

    【讨论】:

      猜你喜欢
      • 2014-03-30
      • 2022-12-11
      • 2012-04-23
      • 2016-07-01
      • 2013-09-22
      • 2018-01-08
      • 1970-01-01
      • 2018-10-09
      • 2015-03-26
      相关资源
      最近更新 更多