Hi I am trying to find the index of a 2d array, but have only been able to find how to index each row at a time. Unfortunately this isn't useful as I cannot find the index for the other after the first indexing statement couldn't find the word in the list.
Here is the code I was attempting to use:
if not button:#code to be ran if in test screen
#print("Test Mode")
time.sleep(0.4)
Wordtotranslate = self.driver.find_element_by_xpath('/html/body/div[4]/div[3]/div/div/div[1]/div[1]/div/div')
Wordtotranslate = Wordtotranslate.text
print(Wordtotranslate)
def in_list():
for i, sublist in enumerate(words_list2d):
if Wordtotranslate in sublist:
return i
return -1
in_list()
The error I get is:
Eng_Index = words_list2d[0].index(Wordtotranslate)
ValueError: 'on' is not in list
In short im looking to find the postion of an element(string) in a 2d array/list in python
Any help will be greatly appreciated
Here's an example of traversing a 2-dimensional array and extracting the index values for elements that match a criteria.
A couple notes:
words_to translate
, maybe you used list.index()
because only care about the first instance, etc.)import collections
words_list2d = [
['here', 'are', 'example'],
['words', 'in', 'a'],
['2d', 'array', 'with'],
['duplicate', 'words', 'duplicate'],
]
words_to_translate = ['example', 'array', 'duplicate', 'words']
word_indexes = collections.defaultdict(list)
for row_index, row in enumerate(words_list2d):
for value_index, value in enumerate(row):
for word in words_to_translate:
if word == value:
word_indexes[word].append((row_index, value_index))
break
for word in word_indexes:
print(f"{word}: {word_indexes[word]}")
Output:
$ python3 find_words_in_2d_array.py
example: [(0, 2)]
words: [(1, 0), (3, 1)]
array: [(2, 1)]
duplicate: [(3, 0), (3, 2)]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.