如果同群組中,英文字不會重複出現的話,可以這樣寫
data = [
['1','A'],
['1','B'],
['1','C'],
['5','C'],
['5','A'],
['8','A'],
['8','C'],
['30','B'],
['30','D'],
['30','E'],
['30','C'],
['30','F'],
['62','H'],
['62','A'],
['62','G'],
['62','C']
]
status = {}
group = []
for row in data:
if not row[0] in status: # 新群組紀錄狀態為空,群組列表加入新群組
group.append(row[0])
status.update({row[0]: ''})
if row[1] == 'A' and not status[row[0]]: # 紀錄狀態為A
status[row[0]] = 'A'
if row[1] == 'C' and status[row[0]] != 'A': # C前沒有A,記錄狀態為change
status[row[0]] = 'change'
for row in data:
if status[row[0]] == 'change' and group.index(row[0]) > 0: # 替換群組名
row[0] = group[group.index(row[0]) - 1]
print(row)
如果沒有人給你正統 python 的答案
就只好加減用底下的程式了
Before:
['1', 'A']
['1', 'B']
['1', 'C']
['5', 'C']
['5', 'A']
['8', 'A']
['8', 'C']
['30', 'B']
['30', 'D']
['30', 'E']
['30', 'C']
['30', 'F']
['62', 'H']
['62', 'A']
['62', 'G']
['62', 'C']
After:
['1', 'A']
['1', 'B']
['1', 'C']
['1', 'C']
['1', 'A']
['8', 'A']
['8', 'C']
['8', 'B']
['8', 'D']
['8', 'E']
['8', 'C']
['8', 'F']
['62', 'H']
['62', 'A']
['62', 'G']
['62', 'C']
listString = [
['1','A'],
['1','B'],
['1','C'],
['5','C'],
['5','A'],
['8','A'],
['8','C'],
['30','B'],
['30','D'],
['30','E'],
['30','C'],
['30','F'],
['62','H'],
['62','A'],
['62','G'],
['62','C']
]
print("Before:")
for row in listString:
print(row)
def change_group(old, new):
for row in listString:
if (row[0]==old):
row[0]=new
is_first='Y'
ex_groupkey=''
groupkey=''
code=''
for row in listString:
if (groupkey!=row[0]):
if (is_first=='Y'):
is_first='N'
ex_groupkey=row[0]
groupkey=row[0]
if ((row[1]=='A') or (row[1]=='C')):
code=row[1]
else:
if (code!='C'):
change_group(groupkey, ex_groupkey)
ex_groupkey=groupkey
groupkey=row[0]
if (row[1]=='A'):
code=row[1]
else:
code=''
else:
if (row[1]=='A'):
if (code==''):
code=row[1]
if (row[1]=='C'):
if (code=='A'):
code=row[1]
print("After:")
for row in listString:
print(row)