2013-03-25 73 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