2016-09-19 73 views
0

我需要创建一个字典,我可以分配一个值来对列表中的同一对象进行分类。请注意,我没有预先存在的值,我希望python分配一个值。以下是我有:如何创建目录以将值分配给列表中的类似项目。

In [38]: post_title_list 
Out[38]: [u'the rfe master list', 
      u'the rfe master list', 
      u'the rfe master list', 
      ...] 

的RFE大师不胜枚举约700次以上,直到我们开始下一个标题是u'the共同问题”。我想为列表中的每个新词组分配一个数字,因此rfe主列表被分配1,直到我们遇到将被分配2的合作问题,依此类推。

我曾尝试以下代码,没有运气:

In [39]: d = dict(zip(post_title_list, range(len(post_title_list))) 
    Out[39]: {u'the rfe master list': '491818'} 

    In [40]: {item: str(i) for i, item in enumerate(post_title_list)} 
    Out[40]: {u'the rfe master list': '491818'} 

    In [41]: dict.fromkeys(post_title_list) 
    Out[41]: {u'the rfe master list': None} 

所需的输出:

Out[42]: {u'the rfe master list': 1, 
      u'the rfe master list': 1, 
      u'the rfe master list': 1, 
      u'the co problem'  : 2, 
      u'the co problem'  : 2, 
      u'expecting delays' : 3, 
      u'denied help   : 4, 
      ...} 

谢谢。

+0

你不能有相同的多个键。你只能有一个''rfe主列表'',而不是多个,如果你添加另一个,它会替换旧的。 –

+0

键在python'dict'中不能相似,而对于不同的键可以有相似的值。 –

+0

词典中的每个键都必须是唯一的,所以您的重复条目的目标是不可能的。如果你真的需要重复的话,你可以创建一个像[('master list',1)]这样的值/数字对列表。 –

回答

1

正如评论中所述,字典需要有唯一的密钥。所以我会建议一个元组列表。 产生所需的输出类似的形式,我认为是这样的:

ctr = 1 

l = [ 
    'a', 
    'a', 
    'a', 
    'a', 
    'a', 
    'a', 
    'a', 
    'a', 
    'b', 
    'b', 
    'b', 
    'b', 
    'b', 
    'b', 
    'c', 
    'c', 
    'c', 
    'c', 
    'c', 
] 

out = [] 
for idx, element in enumerate(l): 
    if idx == 0: 
     out.append((element, ctr)) 
    else: 
     if element != l[idx-1]: 
      ctr = ctr + 1 
     out.append((element, ctr)) 

print(out) 

[('a', 1), 
('a', 1), 
('a', 1), 
('a', 1), 
('a', 1), 
('a', 1), 
('a', 1), 
('a', 1), 
('b', 2), 
('b', 2), 
('b', 2), 
('b', 2), 
('b', 2), 
('b', 2), 
('c', 3), 
('c', 3), 
('c', 3), 
('c', 3), 
('c', 3)] 

更新由于评论

列表的打印方式取决于在哪个开发环境中使用。然而,要有独立于IDE的东西,这应该是这个工作:

for t in out: 
    print(t) 
+0

这很好用,但是当我列出列表时,它看起来像这样: [('a',1),('a',1),('a',1)...] 我怎样才能确保它看起来像你的打印出来(又名垂直)谢谢! – glongo

1

正如您在问题的评论中已经指出的那样,您不能在字典中为同一个键使用多个条目。去会在每部影片只发生一次,并映射到相应数量的字典

方式一:

d = {} 
next_id = 1 
for title in post_title_list: 
    if title not in d: 
     d[title] = next_id 
     next_id += 1 

或者,你可以创建一个列表与一个元组(title,id)对列表中的所有元素:

l = [] 
next_id = 0 
last = None 
for title in post_title_list: 
    if title != last: 
     next_id += 1 
    l.append((title,next_id)) 
    last = title 
+0

这很好用,但是当我打印出列表时,它看起来像这样:[('a',1),('a',1),('a',1)...]我该如何制作确定它看起来像你的打印出来(又名垂直)谢谢! – glongo