[英]Indexing 2d arrays/lists
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) Eng_Index = words_list2d[0].index(Wordtotranslate)
ValueError: 'on' is not in list ValueError: 'on' 不在列表中
In short im looking to find the postion of an element(string) in a 2d array/list in python简而言之,我想在 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.)根据您的假设,您可能需要调整逻辑(例如处理words_to translate
重复words_to translate
,也许您使用了list.index()
因为只关心第一个实例等)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)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.