簡體   English   中英

如何在集合中查找具有特定起始字符串的項目

[英]How to find an item with a specific start string in a set

我有大約一千萬個項目,看起來像這樣:

1234word:something
4321soup:ohnoes
9cake123:itsokay
[...]

現在,我需要快速檢查集合中是否包含具有特定開始的項目。 例如

x = "4321soup"
is x+* in a_set:
     print ("somthing that looks like " +x +"* is in the set!")

我該如何完成? 我已經考慮過使用正則表達式,但是我不知道在這種情況下是否有可能。

^4321soup.*$

是的,可以的。嘗試匹配。如果結果為肯定的,您有。如果None ,則None

不要忘記設置mg標志。

參見演示。

http://regex101.com/r/lS5tT3/28

如果只想與字符串的開頭匹配,請使用str.startswith而不是使用正則表達式,同時還要考慮擁有約1000萬行的行數

#!/usr/bin/python

str = "1234word:something";
print str.startswith( '1234' );

python,考慮到您的內容位於名為“ mycontentfile”的文件中

>>> with open("mycontentfile","r") as  myfile:
...     data=myfile.read()
... 
>>> for item in data.split("\n"):
...     if item.startswith("4321soup"):
...             print item.strip()
... 
4321soup:ohnoes

散列集非常適合完全檢查某些元素的存在。 在您的任務中,您需要檢查起始部分(而不是完整元素)的存在。 這就是為什么更好地使用樹或排序序列而不是哈希機制(python set的內部實現)的原因。

但是,根據您的示例,您似乎想要檢查':'之前的整個零件。 為此,您可以使用這些第一部分來構建集合,然后使用集合檢查存在性將是一件好事:

items = set(x.split(':')[0] for x in a_set) # a_set can be any iterable

def is_in_the_set(x):
    return x in items

is_in_the_set("4321soup")  # True

在這種情況下,重要的是如何以樂觀的方式迭代設置。
由於應該檢查每個結果,直到找到匹配的結果,所以最好的方法是創建一個生成器(列表表達式形式)並執行它,直到找到結果為止。 為此,我應該使用一種方法。

a_set = set(['1234word:something','4321soup:ohnoes','9cake123:itsokay',]) #a huge set
prefix = '4321soup' #prefix you want to search
next(x for x in a_set if x.startswith(prefix), False) #pass a generator with the desired match condition, and invoke it until it exhaust (will return False) or until it find something

我目前正在考慮,最合理的解決方案將是像dicts排序樹(鍵= x和value = y)之類,並且該樹由dicts鍵排序。 -雖然不知道該怎么做– Daedalus Mythos

無需字典樹 ……只需一本字典即可。 如果您將key:value對存儲在字典中,則假設itemdict ,您可以編寫

x = "4321soup"
if x in itemdict:
    print ("something that looks like "+x+"* is in the set!")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM