2013-03-25 37 views
0

我想找到以下情況最好的解決辦法:
我有以下項目:
item1包含test1test2
item2包含test3test4

item3包含test5
superItem其中包含item1,item2item3Python中查找文本

我應該使用哪些方法來達到以下結果;
我得到含有test1
可變check我想收到result可變item1 ...

換句話說: 我想收到的項目的名稱包含相同的文字作爲變量check

什麼是最佳解決方案?

+0

那你試試? – 2013-03-25 10:51:38

+0

@CédricJulien字典集,但我不知道如何命名集 – Arseniy 2013-03-25 10:52:33

回答

1

我假設你將持有字典這些變量,如下面的代碼。

container = { 
    'item1': {'test1', 'test2'}, 
    'item2': {'test3', 'test4'}, 
    'item3': {'test5'} 
} 
    } 
check = 'test1' 

for key in container: 
    if check in container[key]: 
     break 

result = container[key] 
print result 

編輯

我加爲您設置的 - 你用{ }他們。

+0

非常感謝,其實使用'[]'你是對的, 也對我來說必須有'result = key' – Arseniy 2013-03-25 11:10:49

+0

我很樂意提供幫助。 – ceruleus 2013-03-25 11:12:10

2

使用字符串項和列表理解一個簡單的版本:

item1 = ["test1", "test2"] 
item2 = ["test3", "test4"] 
item3 = ["test5"] 
superItem = [item1, item2, item3] 

check = "test1" 
result = [item for item in superItem if check in item] 

>>> result 
[["test1", "test2"]] 
+0

你的意思是套集? – Arseniy 2013-03-25 10:49:41

+0

@Pepelac:沒有關於你所做的和/或示例的更多信息,我認爲這些設置可以幫助你。如果你爲你的問題添加一些精度,我可能可以幫助你更精確地;) – 2013-03-25 10:52:59

+0

@Pepelac:我用一個簡單的解決方案更新了我的答案 – 2013-03-25 10:57:36

1

我使用列表理解的實現。列表名稱('itemn')存儲在superItem字典中,以便您可以在需要時獲取它。

item1 = ["test1", "test2"] 
item2 = ["test3", "test4"] 
item3 = ["test5"] 

superItem = { 
    'item1': item1, 
    'item2': item2, 
    'item3': item3 
} 

check = "test1" 

result = [x for x in superItem if check in superItem[x]] 

print result 

性能測試:

$ time python2.7 sometest.py 
['item1'] 

real 0m0.315s 
user 0m0.191s 
sys 0m0.077s