【问题标题】:Encoding tuples within a list编码列表中的元组
【发布时间】:2017-02-04 18:29:54
【问题描述】:

我有一个元组列表,我想对它们进行编码,有人可以告诉我如何做同样的事情。 例如,在下面的情况下,我想为('Hi','VB')分配一个值,即我想为下面列表中的每个元组分配一个值(整数)(也许它也被称为向量化)。

[('Hi', 'VB'),
 ('remind', 'VB'),
 ('me', 'PRP'),
 ('regarding', 'IN'),
 ('ice', 'JJ'),
 ('cream,', 'NN'),
 ('in', 'VBG'),
 ('around', 'RB'),
 ('11am', 'CD')]

【问题讨论】:

  • 不清楚你在问什么“我想分配一个值(整数)”。示例输出将很有帮助。另外,您尝试过什么来实现这一目标?
  • {key: value for value, key in enumerate(values)} 其中values 是您的原始列表。

标签: python list nlp tuples text-mining


【解决方案1】:

如果你想要dictionary

tuples = [('Hi', 'VB'),
 ('remind', 'VB'),
 ('me', 'PRP'),
 ('regarding', 'IN'),
 ('ice', 'JJ'),
 ('cream,', 'NN'),
 ('in', 'VBG'),
 ('around', 'RB'),
 ('11am', 'CD')]

my_dict = {}
for i, tuple in enumerate(tuples):
  my_dict[tuple] = i

print my_dict
# {('in', 'VBG'): 6, ('regarding', 'IN'): 3, ('me', 'PRP'): 2, ('cream,', 'NN'): 5, ('11am', 'CD'): 8, ('remind', 'VB'): 1, ('Hi', 'VB'): 0, ('around', 'RB'): 7, ('ice', 'JJ'): 4}
print my_dict[('me', 'PRP')]
#=> 2

【讨论】:

    【解决方案2】:

    tuples 在 python 中是 hashable。因此,您可以将它们用作 python 字典中的键。所以这是从元组列表中创建dict 的简单案例。

    values = [1,2,3,4,5,6,7,8,9]
    tuples = [('Hi', 'VB'),
     ('remind', 'VB'),
     ('me', 'PRP'),
     ('regarding', 'IN'),
     ('ice', 'JJ'),
     ('cream,', 'NN'),
     ('in', 'VBG'),
     ('around', 'RB'),
     ('11am', 'CD')]
    
    res_dict = dict(zip(tuples, values))
    

    打印出res_dict -

    {('remind', 'VB'): 2, ('me', 'PRP'): 3, ('11am', 'CD'): 9, ('in', 'VBG'): 7, ('ice', 'JJ'): 5, ('cream,', 'NN'): 6, ('Hi', 'VB'): 1, ('around', 'RB'): 8, ('regarding', 'IN'): 4}
    

    【讨论】:

      猜你喜欢
      • 2015-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多