gpt4 book ai didi

python - 根据先前元素的条件将元素添加到列表

转载 作者:行者123 更新时间:2023-11-28 22:19:33 25 4
gpt4 key购买 nike

我有一个正在阅读的 txt 文件,格式如下:

Event B     0     40
Event B 0 75
Event B 1 30
Event A
Event B 1 50
Event B 1 70
Event A
Event A
Event B 2 40

我正在尝试编写以下逻辑:

对于每个事件 A: 打印自上一个事件 A 以来第一个事件 B 的第 1 列和第 2 列

所以输出如下:

Event B     0     40
Event B 0 75
Event B 1 30
Event A 0 40
Event B 1 50
Event B 1 70
Event A 1 50
Event A N/A N/A
Event B 2 40
etc...

我可以以列表形式读取文件:

with open(event_file) as schedule:
schedule = schedule.readlines()


for i in range(0, len(schedule)):
if schedule[i][0] == 'Event A':
if schedule[i-X][0] == 'Event A':
print(schedule[i-X+1]) # Where X is how many lines before Event A the last one was... but I really dont know how to determine this.. Nor do I know if any of this is the right way to go about it.

希望我说的有道理。

最佳答案

您只需要记住最后一个事件 B:

txt = """Event B  ,   0 ,    40
Event B , 0 , 75
Event B , 1 , 30
Event A
Event B , 1 , 50
Event B , 1 , 70
Event A
Event A
Event B , 2 , 40
"""

# split your data:
data = [ [k.strip() for k in row.strip().split(",")] for row in txt.split("\n")]

rv = []
b = None
for d in data:
if d[0] == "Event A":
# either add the remembered B or N/A's
if b:
rv.append([ d[0], b[1],b[2] ])
else:
rv.append([ d[0], "N/A","N/A" ])
b = None # delete remebered b
continue
elif b == None: # remember first b
b = d
if d and d[0]: # if not empty, add to results
rv.append(d)

print (rv) # print results

输出:

[['Event B', '0', '40'], 
['Event B', '0', '75'],
['Event B', '1', '30'],
['Event A', '0', '40'],
['Event B', '1', '50'],
['Event B', '1', '70'],
['Event A', '1', '50'],
['Event A', 'N/A', 'N/A'],
['Event B', '2', '40']]

关于python - 根据先前元素的条件将元素添加到列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49652950/

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