简体   繁体   English

“对于单位,列举对象”不起作用,我认为应该

[英]“for unit, object in enumerate” not working as I think it should

Could someone please give me an idea how to get round this little code problem I'm having. 有人可以给我一个主意,如何解决我遇到的这个小代码问题。

My bit of code: 我的一点代码:

dictionary = {}      
word_pos_list = []

for unit, object in enumerate(words_list, start = 1):

  if object in dictionary:  
      word_pos_list.append(dictionary[object])    

  else:                                   
      dictionary[object] = unit     
      word_pos_list.append(unit) 

Here is the problem I am having. 这是我遇到的问题。

Take this as an example list of words for the variable 'words_list': ['this', 'sentence', 'is', 'a', 'very', 'very', 'good', 'sentence'] 以此为变量'words_list'的单词列表示例: ['this', 'sentence', 'is', 'a', 'very', 'very', 'good', 'sentence']

The result I would end up with would be: [1, 2, 3, 4, 5, 5, 7, 2] 我最终得到的结果是: [1, 2, 3, 4, 5, 5, 7, 2]

When a word is found again in the sentence it's value from the dictionary is being displayed correctly as shown with the word 'very' (No. 5) but I'm losing the next 'unit' value, in this example it was No. 6, as you can see the next unique word in the sentence ends up being 7. 当再次在句子中找到一个单词时,字典中的值会正确显示,如单词“ very”(第5号)所示,但是我丢失了下一个“ unit”值,在本例中为No。 6,正如您所看到的,句子中的下一个唯一词最终为7。

What can I do to stop this happening? 我该怎么做才能阻止这种情况的发生? Thanks in advance for your time and help. 在此先感谢您的时间和帮助。

It seems like you are not really looking for the position of the word in the sentence, that enumerate gives you, but how many different words you have seen so far. 似乎您并没有真正在寻找该词在句子中的位置enumerate给了您,但是到目前为止您已经看到了多少个不同的词。 For this, you can just check the number of entries that are currently in the dictionary. 为此,您只需检查字典中当前的条目数即可。

dictionary = {}
word_pos_list = []
for word in sentence:   
    if word not in dictionary:
        dictionary[word] = len(dictionary) + 1
    word_pos_list.append(dictionary[word])

For your sentence, word_pos_list will then be [1, 2, 3, 4, 5, 5, 6, 2] 对于您的句子, word_pos_list将为[1, 2, 3, 4, 5, 5, 6, 2]

As mentioned in one of the comments, there doesn't seem to be a really good reason to be using enumerate here. 正如其中一条评论中提到的那样,似乎没有充分的理由在此处使用enumerate It's a little cleaner to manually count the items. 手动计算项目要干净一点。

words_list = ['this', 'sentence', 'is', 'a', 'very', 'very', 'good', 'sentence']

dictionary = {}      
word_pos_list = []

counter = 0
for word in words_list:
    if word not in dictionary:
        counter += 1
        dictionary[word] = counter

    word_pos_list.append(dictionary[word])

print word_pos_list # [1, 2, 3, 4, 5, 5, 6, 2]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM