【问题标题】:Label elements in a duplicate list标记重复列表中的元素
【发布时间】:2021-04-02 18:16:38
【问题描述】:

有什么好办法吗:

    input  = ['hi you', 'hello', 'hi you', 'hello', 'good bye']
    output = [1, 2, 1, 2, 3] 

非常感谢!!

(我刚刚编辑了输入列表。我的案例实际上是新列表,而不是字母列表)

【问题讨论】:

  • output = [ord(x) for x in input] 它能给你想要的吗? 1、2 和 3 是什么意思?字母索引、第一次出现的索引或任意标识符?
  • 如果这不是字母输入列表而是字符串列表怎么办?而1、2、3只是每个字符串的出现顺序
  • 在这种情况下,我会选择几分钟前在此处发布的已删除答案的解决方案。我希望作者回来重写他的答案。
  • 另外,我建议您清楚地解释您的问题,并避免笼统的概括,这会导致我们在这里得到不正确的答案。
  • @LeVuMinhHuy 你能用两个字符串的预期结果编辑我们的分析器吗?

标签: python list


【解决方案1】:

你可以这样解决:

output = [input.index(i) for i in input]

输出中的每个值都将是输入中该索引处的值的第一个索引。如果您希望数组从一次使用开始:

output = [input.index(i) + 1 for i in input]

(尽管您可能希望避免使用内置函数,例如变量名的输入)

【讨论】:

    【解决方案2】:

    ord() 函数给出一个字符的 unicode 值。例如,ord('a') == 97

    在 unicode 以及大多数其他字符编码中,普通字母是按顺序存储的。因此,您可以通过简单地减去ord('a') 来获得任何其他字母的索引,例如:ord('b') - ord('a') == 1ord('z') - ord('a') == 25。当然,您可以添加一个以获得基于 1 的索引。

    利用这些知识,我们可以构建一个可以满足您需求的理解:

    output = [ord(i) - ord('a') + 1 for i in input]
    

    这将为您的示例输入提供所需的结果。但是,如果您的字符串包含任何大写字母或符号,结果可能会很奇怪。例如ord('A') == 65,因此如果您的字符串包含大写字母A,它将被-31 替换。如果您想将大写字母视为相同的用途:

    output = [ord(i.lower()) - ord('a') + 1 for i in input]
    

    【讨论】:

      【解决方案3】:

      最省时的方法是构建从值到第一个遇到的索引的映射:

      >>> data = ['a', 'b', 'a', 'b', 'c']
      >>> index = {}
      >>> for x in data:
      ...     if x not in index:
      ...         index[x] = len(index) + 1
      ...
      >>> index
      {'a': 1, 'b': 2, 'c': 3}
      

      然后简单地映射原始数据:

      >>> [index[x] for x in data]
      [1, 2, 1, 2, 3]
      

      【讨论】:

        【解决方案4】:

        你可以这样做:

        idx_dict, result, counter = {}, [], 1 #idx_dict stores first index of every unique value
        for i in input1:
            if i not in idx_dict: #stores the first index of every unique value in idx_dict 
                idx_dict[i] = counter
                counter += 1
            result.append(idx_dict[i]) #for every value encountered get its first index from the idx_dict and append to result list
        

        这基本上解决了'n'次迭代的问题

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-05-07
          • 2021-08-17
          • 1970-01-01
          • 2013-01-30
          • 1970-01-01
          • 2021-03-25
          • 1970-01-01
          相关资源
          最近更新 更多