简体   繁体   English

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

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

I'm wondering how I can efficiently check whether a value is inside a given list of tuples. 我想知道如何有效地检查一个值是否在给定的元组列表中。 Say I have a list of: 说我有一个清单:

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

how can I check whether a given word is inside the list, ignoring the second value of the tuples? 如何检查给定单词是否在列表中,忽略元组的第二个值? If it was just a word I could use 如果这只是我可以使用的一个词

if "the" in wordlist:
   #...

but this will not work, is there something along the line this i can do? 但是这不起作用,我能做些什么吗?

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

可以使用哈希

>>> word in dict(list_of_tuples)

Use any : 使用任何

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

Lookup of the word in the list will be O(n) time complexity, so the more words in the list, the slower find will work. 查找列表中的单词将是O(n)时间复杂度,因此列表中的单词越多,查找速度越慢。 To speed up you may sort a list by word as a key alphabeticaly and then use binary search - search of the word becomes log(N) complexity, but the most efficient way is to use hashing with the set structure: 为了加快速度,您可以按字母顺序对列表进行排序,然后使用二进制搜索 - 搜索单词变为log(N)复杂度,但最有效的方法是使用散列与设置结构:

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

O(1), independent of how many words are in the set. O(1),与集合中的单词数无关。 BTW, it guarantees that only one instance of the word is inside the structure, while list can hold as many "the" as many you append. 顺便说一句,它保证了单词中只有一个实例在结构中,而list可以保存尽可能多的“the”。 Set should be constructed once, add words with the .add method(add new word is O(1) complexity too) 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