I need to write the values ​​in a two-dimensional list by sorting the values ​​of other lists:

for i, snt in enumerate(text_list): for j, wrd in enumerate(dict): # print (i,j) matrix[i][j] = snt.count(wrd) 

Error: IndexError: list assignment index out of range

print (i,j) - executes with all index values ​​as necessary

    2 answers 2

    You have an error: Going beyond the bounds of the list range.

    In Python, in order to change the value of a list item by index, you need to somehow first add this item to the list.

    And it will work like this:

     for i, snt in enumerate(text_list): matrix.append([]) # append new sublist to the list for j, wrd in enumerate(dict): matrix[i].append(snt.count(wrd)) # append the value to the sublist 

    At each iteration of the outer loop, we create an empty sublist and add it to the list. The inner loop adds an element to the sublist.

    After adding items to them can be accessed by index.

    And the print function doesn't care what indices to display.

    • cool! thank! - Vladimir Vasilev

    To create a matrix for counting the repetition of words in sentences, given text (as a list of sentences specified as a list of words):

     matrix = [[sentence.count(word) for word in dict_] for sentence in text] 

    In your case, the error is because you probably expected the matrix[i][j] = value construction to create a new (i, j) element in the matrix. In Python, lists do not create new items by assigning simple indexes. Therefore, if matrix[i][j] did not exist, then the assignment will throw an IndexError error.

    • and thank you! I am reconstructed from PCP to a python, but I have not yet found an intelligent manual on the Internet. another question, and the count method turns out not to look for the word in the sentence, but for the substring in the string. What is not the same. If I need exactly the frequency of the word in the sentence, then how to be, are there any standard functions? - Vladimir Vasilev
    • @VladimirVasilev Python Materials in Bulk is one of the most popular languages. For people familiar with programming, you can start with the official introductory manual (available also in the form of a book in Russian and online) ¶ I explicitly wrote in the answer that sentence is a list (and not a string) just because otherwise the substrings are searched in count () . If you don’t know how to break a sentence into individual words, then ask a separate Stack Overflow question: depending on your specific requirements, the solution can use simple words = sentence.split() call, and regex, and TweetTokenizer from nltk, and so on. - jfs