基于字符串模式

时间:2017-05-24 15:44:59

标签: python regex python-2.7

我有一张桌子(列表清单)。示例输出如下:

table = ['dd03', 'ff0000', 'a30b32', '000000', '234fas', '00ffff', 'ffffff', '0000ff', '0200ff']

我想删除列表中包含“ff'”组合的所有元素。在他们或至少2/6字符中的元素属于那个角色。

我已经完成了一项列表理解,但是它显然效率不高,而且可以用更少的代码完成。

    table = [[part for part in my_list if part != 'ffffff'] for my_list in table]
    table = [[part for part in my_list if part != 'ffff00'] for my_list in table]
    table = [[part for part in my_list if part != 'ff0000'] for my_list in table]
    table = [[part for part in my_list if part != '0000ff'] for my_list in table]
    table = [[part for part in my_list if part != '00ffff'] for my_list in table]
    table = [[part for part in my_list if part != 'ffff'] for my_list in table]
    table = [[part for part in my_list if part != 'ff'] for my_list in table]
    table = [[part for part in my_list if part != 'ffff02'] for my_list in table]
    table = [[part for part in my_list if part != '0200ff'] for my_list in table]

我想可能会为找到的模式设置一个正则表达式变量,然后删除匹配的元素......但是我不太熟悉这个包并在这种情况下实现它。

任何方向都会受到赞赏。

干杯

5 个答案:

答案 0 :(得分:2)

试试这个:

table = ['dd03', 'ff0000', 'a30b32', '000000', '234fas', '00ffff', 'ffffff', '0000ff', '0200ff']
filtered_table = [item for item in table if item.count('f') < 2]

答案 1 :(得分:1)

简单的收容检查应该有效:

[item for item in table if 'ff' not in item]

'至少2/6'条件非常冗余(长度为常数6),足以检查项目是否包含'ff'

答案 2 :(得分:0)

您可以遍历列表中的元素并弹出()包含子字符串的那些元素:

state_size

答案 3 :(得分:0)

你可以像{i}这样获得没有<div className="container"> <div className="row"> <div className="col-sm-4 col-sm-offset-4"> Center content here </div> </div> </div>的元素,

for item in list_of_items:
    if "ff" in item:
        list_of_items.pop(list_of_items.index(item))

答案 4 :(得分:0)

这取决于'f'的位置:

table = ['dd03', 'ff0000', 'a30b32', '000000', '234fas', '00ffff', 'ffffff', '0000ff', '0200ff']
table = [x for x in table if 'ff' not in x] # since it's at least 'ff', if 'ffff' was found, 'ff' is in 'ffff', so it's true for all 'f'*n : n>=2
print(table) # => ['dd03', 'a30b32', '000000', '234fas']

定位免费版:

table = ['dd03', 'ff0000', 'a30b32', '000000', '234fas', '00ffff', 'ffffff', '0000ff', '0200ff']
table = [x for x in table if x.count('f')<2]
print(table) # => ['dd03', 'a30b32', '000000', '234fas']