簡體   English   中英

將列表項中的字母替換為數字

[英]Replace letters in list item to numbers

我是新來的,對編程也很陌生。 我最近開始學習 Python 來學習如何在我的日常任務中實現流程自動化。

我正在比較通過將 2 個 Excel 文件中的 2 列轉換為列表而創建的 2 個列表。 列表主要包含數字,但有些項目同時包含整數和字母,我相信這會導致成為字符串而不是 integer。 我想將字母轉換為數字,以獲得能夠操作、比較等的整數列表。有什么辦法可以做到這一點嗎? 我一直在使用 openpyxl 來訪問我的 Excel 文件。 下面是我想做的一個例子。

例如:輸入

list1 = [8635, 6227, '8651FRT', '8651BK','8295INSERT', 8295]

output

newlist1 = [8635, 6227, 865101, 865102,829503, 8295]

我想用 01 替換“FRT”,用 02 替換“BK”,用 03 替換“INSERT”。非常感謝您的幫助。 謝謝。

一種方法是定義一個帶有要替換的值的dict ,然后是re.sub以提取和替換這些值。

import re

replace = {"FRT": "01", 'BK': "02", 'INSERT': "03"}

list1 = [8635, 6227, '8651FRT', '8651BK', '8295INSERT', 8295]

print(
    [int(re.sub(r"([A-Za-z]+)",
            lambda x: replace.get(x.group(1), ""), str(x))) for x in list1]
)
[8635, 6227, 865101, 865102, 829503, 8295]

您可以使用:

newlist1 = [int(str(item).replace('FRT', '01').replace('BK', '02').replace('INSERT','03')) for item in list1]

如果您需要更多信息,請使用help(str)找到所需的所有信息。

你可以寫一個 function 來替換一個項目(我看不到一個簡單的快捷方式),然后你可以在列表理解中循環它。

import re

mappings = {'FRT': '01', 'BK': '02', 'INSERT': '03'}

def replace(val):
    
    if isinstance(val, int):
        return val
    
    m = re.match('(\d+)(\D+)$', val)
    if m:
        key = m.group(2)
        if key in mappings:
            return int(m.group(1) + mappings[key])

    raise ValueError('could not do replacement for {}'.format(val))


list1 = [8635, 6227, '8651FRT', '8651BK','8295INSERT', 8295]

print([replace(x) for x in list1])

給出:

[8635, 6227, 865101, 865102, 829503, 8295]

它不是最好的例子。 你可以做得更快更好。 但我想這是可以理解的,你如何接近它。 :)

list1 = [8635, 6227, '8651FRT', '8651BK','8295INSERT', 8295]
newlist = []
# Check every item in list
for item in list1:
  # If its a integer, add to newlist
  if isinstance(item, int):
    newlist.append(item)
    continue
  # Else check and replace
  if 'FRT' in item:
    item = item.replace('FRT', '01')


 # Check other exception here
  
   newlist.append(int(item))

您可以遍歷您的值列表。 當你遇到一個非整數時,你可以去掉字母,append 是一個遞增計數器。 然后將此計數器添加到映射字典中,以確保每次都使用相同的值。 這不應該需要任何前期工作或映射。 這確實假設字母在末尾或在您的數字之后。

import re
list1 = [8635, 6227, '8651FRT', '8651BK','8295INSERT', 8295,8295 , '8295INSERT', '8651BK' , '8295INSERT', '8651BK',6227 , ]
mapping = {}
counter_ = 1
output_list = []
for x in list1:
    if isinstance(x, int):
        output_list.append(x)
        pass
    else:
        output = re.split(r'(\d+)', x)
        try:
            val = mapping[output[2]]
            output[2] = val
            output_list.append(''.join(output[1:]))
        except:
            mapping[output[2]] = '0'+str(counter_)
            output[2] = '0'+str(counter_)
            output_list.append(''.join(output[1:]))
        counter_ += 1

newlist = [int(x) for x in output_list]

您可以將字符串替換為變量的計數。 也許你正在尋找這個。

list1 = [8635, 6227, '8651FRT', '8651BK','8295INSERT', 8295]
mod = []
c = 1

for val in list1:
    if (str(val).isnumeric()): mod.append(val)
    else:
        n = len(val)
        for i in range(n):
            if (not val[i].isnumeric()):
                if (c<10): 
                    mod.append(int(val[0:i]+'0'+str(c)))
                    c+=1
                    break
                else: 
                    mod.append(int(val[0:i]+str(c)))
                    c+=1
                    break

print(mod)

謝謝

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM