繁体   English   中英

检查单词是否在元组列表中

[英]Check if word is inside of list of tuples

我想知道如何有效地检查一个值是否在给定的元组列表中。 说我有一个清单:

("the", 1)
("check", 1)
("brown, 2)
("gary", 5)

如何检查给定单词是否在列表中,忽略元组的第二个值? 如果这只是我可以使用的一个词

if "the" in wordlist:
   #...

但是这不起作用,我能做些什么吗?

if ("the", _) in wordlist:
   #...

可以使用哈希

>>> word in dict(list_of_tuples)

使用任何

if any(word[0] == 'the' for word in wordlist):
    # do something
for tupl in wordlist:
    if 'the' in tupl:
        # ...

查找列表中的单词将是O(n)时间复杂度,因此列表中的单词越多,查找速度越慢。 为了加快速度,您可以按字母顺序对列表进行排序,然后使用二进制搜索 - 搜索单词变为log(N)复杂度,但最有效的方法是使用散列与设置结构:

'the' in set((word for word, _ in a))

O(1),与集合中的单词数无关。 顺便说一句,它保证了单词中只有一个实例在结构中,而list可以保存尽可能多的“the”。 Set应该构造一次,用.add方法添加单词(添加新单词也是O(1)复杂度)

words,scores = zip(*wordlist)

将单词列表拆分为单词列表和分数列表

print "the" in words

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM