gpt4 book ai didi

python - 迭代列表时检查每 3 个连续元素是否遵循某种模式

转载 作者:太空宇宙 更新时间:2023-11-03 21:38:11 25 4
gpt4 key购买 nike

我有一个元素列表,其中每 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"]

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

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, '开始1')
(1, '开始2')
(1,'结束:3')
(1,'结束:4')
(2,'中/1')
(2, '结束:2')
(2, '开始4')
(2, '开始5')
(3, '结束:1')
(3,'中/3')
(3,'中/4')
(3, '结束:5')

最佳答案

您可以使用源列表上的简单循环和一些检查来实现这一点:

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) ))

关于python - 迭代列表时检查每 3 个连续元素是否遵循某种模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53107507/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com