簡體   English   中英

使用字典將列表中的字符串替換為字符串列表

[英]Replace a string in a list with a list of strings using a dictionary

我正在嘗試使用映射到字符串列表的后續字典替換以下列表中的第一個字符串。

id_list = ['40000', '58962', '85496']
id_dict = {'10000': ['10001','10002','10003'], '40000': ['40001','40002','40003']}

使用定義的 function,例如:

def find_replace_multi_ordered(string, dictionary):
    # sort keys by length, in reverse order
    for item in sorted(dictionary.keys(), key = len, reverse = True):
        string = re.sub(item, dictionary[item], string)
    return string

# Credit: http://pythoninthewyld.com/2018/03/12/dict-based-find-and-replace-deluxe/

在以下 for 循環中:

for i in id_list:

    if id_list[0][-4:] == '0000':
        id_list.replace(find_replace_multi_ordered(i, id_dict))

    else:
        pass

print(id_list)

這適用於字符串到字符串字典的映射,但會導致 TypeError 用於 sting 到列表的映射。

錯誤:

TypeError: unhashable type: 'list'

所需的 output 如下:

id_list = [['40001','40002','40003'], '58962', '85496']

感謝您的任何建議!

有更容易,或者列表的每個值,如果它在dict中,只需用指向的值替換,如果它不存在,則保留該值

id_dict.get(item, item)的詳細信息

  • 第一item是要查看的鍵,用於檢索值
  • 第二item是默認值,如果沒有找到key
id_list = ['40000', '58962', '85496']
id_dict = {'10000': ['10001','10002','10003'], '40000': ['40001','40002','40003']}

id_list = [id_dict.get(item, item) for item in id_list]
print(id_list) # [['40001', '40002', '40003'], '58962', '85496']

它做你想做的事嗎?

id_list = ['40000', '58962', '85496']
id_dict = {'10000': ['10001','10002','10003'], '40000': ['40001','40002','40003']}

X = [
    item if item not in id_dict else id_dict[item] for item in id_list
]
print(X) # [['40001', '40002', '40003'], '58962', '85496']

暫無
暫無

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

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