【问题标题】:How to assign same values in dictionary to another list of strings如何将字典中的相同值分配给另一个字符串列表
【发布时间】:2021-03-02 23:01:44
【问题描述】:

我正在尝试将字符串转换为数字,然后为另一个字符串列表中的相同单词分配相同的值。假设我有如下字符串 A 。我使用字典转换为值,如下面的代码。现在我需要为列表 B 中的相同字符串分配相同的值,输出应该类似于 res_B

A='hello world how are you doing'` 
res_A = [1, 2, 3, 4, 5, 6]

B=['hello world how', 'hello are' ,'hello', 'hello are you doing']
res_B = [[1,2,3],[1,4],[1],[1,4,5,6]]
A='hello world how are you doing'
d = {}
res_A = [d.setdefault(word, len(d)+1) for word in A.lower().split()]

【问题讨论】:

    标签: python string list for-loop


    【解决方案1】:
    # map words from A into indices 1..N
    mapping = {k: v for v, k in enumerate(A.split(), 1)}
    # find mappings of words in B
    B_res = [[mapping[word] for word in s.split()] for s in B]
    

    【讨论】:

    • 我将映射更改为字典理解。这种方式更具可读性。
    • 这里当然没有错误检查,所以不要在生产代码中使用。至少应该检查word 是否存在于mapping 中。
    【解决方案2】:

    再次使用列表推导式,以及之前的同一个字典:

    res_B = [
        [d[word] for word in phrase.lower().split()]
        for phrase in B
    ]
    

    【讨论】:

      【解决方案3】:

      这是一个循序渐进的实用方法

      # Create a lookup dictionary
      lookup = {word: index for word, index in zip(A.split(' '), res_A)}
      
      # Map every sentence to be replaced with lookup values per word
      res_B = [list(map(lambda x: lookup[x], sentence.split(' '), 
                        sentence)) for sentence in B]
      

      【讨论】:

        猜你喜欢
        • 2023-01-13
        • 1970-01-01
        • 2020-12-07
        • 1970-01-01
        • 1970-01-01
        • 2021-10-13
        • 2017-08-24
        • 2019-10-08
        • 1970-01-01
        相关资源
        最近更新 更多