在遍历列表时,检查每3个连续元素遵循一个模式

时间:2018-11-01 18:47:03

标签: python

我有一个元素列表,应该每3个连续的元素遵循一个模式,但是某些数据丢失了,我想用" "填充缺少数据的位置。

例如,对于下面的列表,我要检查从第一个元素开始的每个第三个元素都包含单词"start",从第二个元素开始的每个第三个元素都包含"/",最后是每个第三个元素从第三个元素开始的元素包含":"

所以这个:

list = ["start1", "mid/1", "end:1", "start2", "end:2", "mid/3", "end:3"]

会变成这样:

list = ["start1", "mid/1", "end:1", "start2", " ", "end:2", " ", "mid/3", "end:3"]

我设法使用下面的代码打印出每个第3个元素和步骤号,但是在实际插入" "

时遇到了麻烦

data = ["start1", "mid/1", "end:1", "start2", "end:2", "mid/3", "end:3", "start4", "mid/4", "end:4", "start5", "end:5"]

    for step, init_info in enumerate(data[:3:], 1):
        for elem, info in enumerate(data[step-1::3], 1):
            print(step, info)

这将返回:

(1, 'start1') (1, 'start2') (1, 'end:3') (1, 'end:4') (2, 'mid/1') (2, 'end:2') (2, 'start4') (2, 'start5') (3, 'end:1') (3, 'mid/3') (3, 'mid/4') (3, 'end:5')

2 个答案:

答案 0 :(得分:2)

您可以通过对源列表进行简单循环并进行一些检查来实现:

l = ["start1", "mid/1", "end:1", "start2", "end:2", "mid/3", "end:3"]

# defines which position must hold what thing in it to be not substituted
d = {0:"start", 1:"/", 2:":"}

# target list    
k = [] 

# counts the insertions, to adjust dict lookup
inserted = 0

for idx,e in enumerate(l):
    must_be_in_else_substitute = d.get( (idx+inserted) % 3)
    if must_be_in_else_substitute in e:
        k.append(e)
    else:
        inserted+=1
        k.extend([" ",e])
print(k)

输出:

['start1', 'mid/1', 'end:1', 'start2', ' ', 'end:2', ' ', 'mid/3', 'end:3']

您可以按照@timgeb的建议使用生成器,不知道大多数“规则”的可重用性是什么样的。这样做与上面的代码大致相同,只是更懒:

l = ["start1", "mid/1", "end:1", "start2", "end:2", "mid/3", "end:3"]    

def insert_something_if_at_pos_not_in(rules,data,tbi=" "):
    """No idea how to docstring this in a sensible way - lets say 
    it does what the OP described :o)"""
    inserted=0
    rule_max = max(rules.keys())+1
    for idx,e in enumerate(data):
        must_be_in = rules.get( (idx+inserted) % rule_max)
        if must_be_in in e:
            yield e
        else:
            yield " "
            yield e

print(    list(insert_something_if_at_pos_not_in({0:"start", 1:"/", 2:":"},l) ))

答案 1 :(得分:-1)

.get()方法允许您在未插入默认值的情况下输入默认值。但这是字典的一种方法。 尝试将其与.append配对以创建您的列表