iT邦幫忙

0

初學 Python 欄位字串更改及排序問題(已解決)

  • 分享至 

  • xImage

大家好,如下圖截圖,想詢問:
A欄中相同的數字視為一群組,如果每一群組中,B欄的C前面沒有A,那A欄的數字就要替換成上一個數字

https://ithelp.ithome.com.tw/upload/images/20210730/20139987uIURFUdxFK.jpg
像這張圖,A欄的5就會全部變成1;30就會全部變成8

已上網爬文許久且試了許多方法,但還是跑不出來,想請大家幫忙解答,謝謝!

討論跟思考 盡量不要把 分組用的符號 與 內容 使用相同的.
A欄,B欄 跟 裡面的 A.
如果每一群組中,B欄的C前面沒有A, <-- 這樣不太適合思考.
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 個回答

0
uobik
iT邦新手 4 級 ‧ 2021-08-01 01:33:17
最佳解答

如果同群組中,英文字不會重複出現的話,可以這樣寫

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)
0
海綿寶寶
iT邦大神 1 級 ‧ 2021-07-31 14:57:35

如果沒有人給你正統 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)

我要發表回答

立即登入回答