在数组数组中使用“ in”

雅克琳

我有一个列表列表,所以是二维数组。我试图用来in弄清楚字符串是否在这些数组中。因此if word in wordlist:,我没有这样做,而是在使用:

for i in range(len(wordlist)):
   if word in wordlist[i]:
      wordlist[i][2] += 1 #this accounts for the frequency of a word in a file
if (i + 1 == len(wordlist) and word !=wordlist[len(wordlist)-1]):
   wordlist.append([word,linenum,1])

有没有更优雅的方式做到这一点?

编辑:样本wordlist

[['civilizati', 1, 1], ['of', 1, 1], ['science', 2, 1], ['is', 2, 1], ['knowledge', 3, 1], ['is', 3, 1]]

编辑编辑:

我想我不清楚我的问题。如果我使用的是一维列表,则可以执行以下操作:

if(word in wordlist1d):
   print("It's here")
else:
   wordlist1d.append(word)

这比我的for循环怪诞要优雅得多但是,由于wordlist不是1d,因此即使word在wordlist的子列表中,wordlist中的语句word也永远不会返回true。我想知道是否有比使用该for循环更优雅的方法

布莱克金

我建议用一个else子句做一个循环

for sublist in wordlist:
    if word == sublist[0]:  # compare directly with the relevant part of the sublist
        sublist[2] += 1
        break  # we only will match at most once, so break after finding one
else:    # this clause is run if no break was hit
    wordlist.append([word, linenum, 1])

一种更有效的方法可能是使用从单词到lineno, count子列表的字典映射搜索字典是O(1),而不是O(n)搜索列表。为了使代码适用于找不到的单词,可以使用以下setdefault方法:

d = {}
for word, lineno in document:
    d.setdefault(word, [lineno, 0])[1] += 1 # works whether or not word was in d before

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章