【问题标题】:Convert elements in sublist to keys in dictionary and append to new list with sublists将子列表中的元素转换为字典中的键并使用子列表附加到新列表
【发布时间】:2021-10-22 13:33:03
【问题描述】:

我正在尝试创建一个列表,其中包含基于另一个子列表列表中的元素的字典中的键子列表(数据如下)。

我有一个函数试图遵循这个逻辑:

  1. 查看子列表中的元素是否与字典中的任何精确值匹配
  2. 如果是,则将关联的字典键附加到新列表中的子列表中
  3. 如果不是,请尝试将元素转换为整数并将其附加到新列表中的子列表中
  4. 如果这不起作用,请将整个子列表附加到一个全新的列表中
  5. 返回包含从原始文件中的字符串转换而来的整数子列表的列表以及包含无法转换的子列表的列表

我希望逻辑是有道理的。感谢这个问题 (Replacing elements in a sublist with keys from a dictionary based on matches with dictionary values) 以前版本中的一些 cmets,我已经编辑了代码和字典,所以 re.search 函数现在可以工作了。下面是新代码:

import re

def conversion(d, file):
    key_list = list(d.keys())
    for i in range(0, 21):
        for j in file:
            for k in j:
                good1 = []
                good1a = []
                good2 = []
                good2a = []
                bad1 = []
                bad2 = []
                if k == d[i]:
                    good1a.append(key_list[i])
                    good1.append(good1a)
                    if isinstance(int(k), int):
                        if int(k) <= 20:
                            good2a.append(int(k))
                            good2.append(good2a)
                        else:
                            bad1.append(j)
                    else:
                        bad2.append(j)
    list1 = []
    list2 = []
    list1.append(good1)
    list1.append(good2)
    list2.append(bad1)
    list2.append(bad2)
    return list1, list2

但是,这不是我期望的输出:

([[], []], [[], []])

这可能与我的列表的放置或类似的东西有关,但我对 python 真的很陌生,我还没有遵循事情应该去哪里的逻辑。

任何帮助将不胜感激!

非常感谢,

卡罗来纳

数据:

d = {0: "zero, null",
    1: "one, un, eins",
    2: "two, deux, zwei",
    3: "three, trois, drei",
    4: "four, quatre, vier",
    5: "five, cinq, funf",
    6: "six, sechs",
    7: "seven, sept, sieben",
    8: "eight, huit, acht",
    9: "nine, neuf, neun",
    10: "ten, dix, zehn",
    11: "eleven, onze, elf",
    12: "twelve, douze, zwolf",
    13: "thirteen, treize, dreizehn",
    14: "fourteen, quatorze, vierzehn",
    15: "fifteen, quinze, funfzehn",
    16: "sixteen, seize, sechzehn",
    17: "seventeen, dix-sept, siebzehn",
    18: "eighteen, dix-huit, achtzehn",
    19: "nineteen, dix-neuf, neunzehn",
    20: "twenty, vingt, zwanzig"}

file = [['16', '10', '8', '3', '7'], ['8', '9', '19', '20', '4'], ['sechs', 'acht', 'sechzehn', 'funf', 'null'], ['1', '30', '2', '5', '7'], ['vierzehn', 'eins', 'zwei', 'neun', 'drei'], ['six', 'neuf', 'seize', 'zero'], ['fourteen', 'eleven', 'forteen', 'eight', 'twenty'], ['douze', 'onze', 'huit', 'quinze', 'sept'], ['18', '9', '9', '22', '4'], ['un', 'trois', 'quatorze', 'dix-huit', 'vingt'], ['five', 'three', 'nineteen', 'twenty', 'zero'], ['einundzwanzig', 'vierzehn', 'eins', 'zwei', 'vier']]

【问题讨论】:

    标签: python regex dictionary for-loop if-statement


    【解决方案1】:

    试试这个:

    import re
    
    def conversion(d, file):
        list1 = []
        list2 = []
        for key, value in d.items():
            for i in file:
                list3 = []
                for j in i:
                    good = []
                    if re.search(fr"\b{re.escape(j)}\b", value):
                        good.append(key)
                        list3.append(good)
                    else:
                        try:
                            good.append(int(j))
                            list3.append(good)
                        except:
                            bad = []
                            bad.append(i)
        list1.append(list3)
        list2.append(bad)
        return list1.Append(list2)
    

    【讨论】:

    • 请解释变化。
    • return list1.Append(list2) @Sujay 这是我的改变 Sujay 先生请加我点 +1。谢谢。
    • 您好安东尼奥,感谢您的回复!不幸的是,当我尝试运行它时,输出为“无”。如果我将 list1.append(list2) 放在返回行上方并返回 list1,我会得到与以前相同的输出。
    【解决方案2】:

    使用 for 循环尝试通过正则表达式单词边界将子列表中的每个 number 与字典中的值(完整写入的数字)匹配。如果匹配,将key添加到匹配列表中对应的数字并打破循环;如果number 不在字典中的任何拼写数字中,则使用try/expect 检查number 是否可以转换为整数。如果可以转换,则将整数添加到sublist_match,否则添加到sublist_no_match

    def conversion(d, file):
        matched = []
        no_match = []
        for sublist in file:
            sublist_match = []
            sublist_no_match = []
            for number in sublist:
                for key, str_values in d.items():
                    if re.search(fr"\b{re.escape(number)}\b", str_values):
                        sublist_match.append(key)
                        break
                else:
                    try:
                        num_item = int(number)
                    except ValueError:
                        sublist_no_match.append(number)
                    else:
                        sublist_match.append(num_item)
    
            matched.append(sublist_match)
            no_match.append(sublist_no_match)
    
        return [matched, no_match]
    
    result = conversion(d,file)
    print(result)
    

    结果的输出

    [[[16, 10, 8, 3, 7],
      [8, 9, 19, 20, 4],
      [6, 8, 16, 5, 0],
      [1, 30, 2, 5, 7],
      [14, 1, 2, 9, 3],
      [6, 9, 16, 0],
      [14, 11, 8, 20],
      [12, 11, 8, 15, 7],
      [18, 9, 9, 22, 4],
      [1, 3, 14, 18, 20],
      [5, 3, 19, 20, 0],
      [14, 1, 2, 4]],
     [[], [], [], [], [], [], ['forteen'], [], [], [], [], ['einundzwanzig']]]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-06
      • 1970-01-01
      • 2023-02-25
      • 1970-01-01
      • 2018-09-28
      • 1970-01-01
      • 2023-01-10
      • 1970-01-01
      相关资源
      最近更新 更多