【问题标题】:python pattern cutting of strings in a list列表中字符串的python模式切割
【发布时间】:2014-06-24 02:44:03
【问题描述】:

我有一个字典变量“d”,其中键、整数和值作为字符串列表。

368501900 ['GH131.hmm  ', 'CBM1.hmm  ']
368499531 ['AA8.hmm  ']
368500556 ['AA7.hmm  ']
368500559 ['GT2.hmm  ']
368507728 ['GH16.hmm  ']
368496466 ['AA2.hmm  ']
368504803 ['GT21.hmm  ']
368503093 ['GT1.hmm  ', 'GT4.hmm  ']

代码是这样的:

d = dict()

for key in d:
    dictValue = d[key]

    dictMerged = list(sorted(set(dictValue), key=dictValue.index))
    print (key, dictMerged)

但是,我想删除列表中数字之后的字符串,这样我就可以得到这样的结果:

368501900 ['GH', 'CBM']
368499531 ['AA']
368500556 ['AA']
368500559 ['GT']
368507728 ['GH']
368496466 ['AA']
368504803 ['GT']
368503093 ['GT']

我认为应该在 dictValue 和 dictMerged 之间插入代码,但我无法制定逻辑。 请问有什么想法吗?

【问题讨论】:

    标签: python string parsing pattern-matching cut


    【解决方案1】:

    在开头导入这个

        import re
    

    现在在 dictValue 和 dictMerged 之间使用这条线

        new_dict_value = [re.sub(r'\d.*', '', x) for x in dictValue]
    

    然后在下一行使用 new_dict_value

    【讨论】:

    • 正则表达式和oneliner for循环!而已!非常感谢!
    【解决方案2】:

    字符串对象有一个很好的.isdigit() 方法。以下是一些用于清理数据的非re 解决方案。

    简单的旧循环:

    values = ['GT1.hmm  ', 'GT4.hmm  ']
    clean_values = []
    for item in values:
        clean_item = []
        for c in item:
            if c.isdigit():
                break
            clean_item.append(c)
        clean_values.append("".join(clean_item))
    

    使用StopIteration 异常在生成器表达式中充当break 的列表推导:(注意在列表推导中使用此stop() 方法不起作用,它需要生成器表达式,通常用 () 表示,但在 .join() 内部,这些是可选的。

    def stop():
        raise StopIteration
    
    values = ['GT1.hmm  ', 'GT4.hmm  ']
    clean_values = ["".join(c if not c.isdigit() else stop() for c in item) for item in values]
    

    使用itertools.takewhile 进行列表理解:

    from itertools import takewhile
    
    values = ['GT1.hmm  ', 'GT4.hmm  '] 
    clean_values = ["".join(takewhile(lambda c: not c.isdigit(),item)) for item in values]
    

    示例来自:

    http://tech.pro/tutorial/1554/four-tricks-for-comprehensions-in-python#breaking_the_loop

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-17
      • 1970-01-01
      • 2014-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多