Iterate through multidimensional lists?

Sorry if the obvious question is, I'm new and my google-fu didn't help me.

I am writing a tool that searches for text for alliteration. I have a multidimensional list: [[e, a, c, h], [w, o, r, d], [l, o, o, k, s], [l, i, k, e], [ t, h, i, s]]

I want to iterate over the items in the main list, checking the index [0] of each item to see if it is equal to the index [0] of the FOLLOWING element.

 def alit_finder(multi_level_list):
  for i in multi_level_list:
   if i[0] == multi_level_list[i + 1][0] and i != multi_level_list[-1]:
    print i, multi_level_list[i + 1] 

I get TypeError: can only a list of concatenations (and not "int") for the list.

So, [i + 1] is not the right way to indicate "an element that has an index equal to i plus one." However, [+ 1] does not work: it seems to return ANY two words in the list that have the same letter in the word [0].

How can I refer to the "next element" in the instructions for this?

ETA: Thanks everyone! I appreciate your time and explanations regarding what I did wrong here!

+4
source share
4 answers

In the usual for each cycle, like you, you only get access to one element at a time:

for x in lst:
    print("I can only see", x)

So you need to iterate over the indices, for example:

for i in range(len(lst) - 1):
    print("current =", lst[i], "next =", lst[i+1])

By the way, as a rule, it is recommended to use variables with a name ito always refer to loop indices. In the source code, part of the confusion is what you first tried to use ias an element of a list, and later as an index, and there cannot be both!

0
source

I think you need something like this:

def alit_finder(multi_level_list):
    l=len(multi_level_list)
    for i in xrange(l-1):
        if multi_level_list[i][0] == multi_level_list[i + 1][0]:
            print multi_level_list[i], multi_level_list[i + 1] 
li=[['e','a','c','h'], ['w','o','r','d'], ['l','o','o','k','s'], ['l','i','k','e'], ['t','h','i','s']]
alit_finder(li)

Result:

['l', 'o', 'o', 'k', 's'] ['l', 'i', 'k', 'e']
0

x :

def alit_finder(multi_level_list):
  for i, x in enumerate(multi_level_list):
    if i == len(multi_level_list) - 1:
      break # prevent index out of range error
    if x[0] == multi_level_list[i + 1][0] and x != multi_level_list[-1]:
      return x, multi_level_list[i + 1]

word_list = [['e','a','c','h'], ['w','o','r','d'], ['l','o','o','k','s'],
             ['l','i','k','e'], ['t','h','i','s']]

print alit_finder(word_list)
# (['l', 'o', 'o', 'k', 's'], ['l', 'i', 'k', 'e'])
0

- :

matching_indices = [i for i, (w1, w2) in enumerate(zip(multi_level_list, multi_level_list[1:])) if w1[0] == w2[0]]
0

All Articles