2024-06-24 12:57:04 发布
网友
我想为以下情况找到最佳解决方案: 我有以下物品:item1包含test1和test2item2包含test3和test4 和item3包含test5 和superItem,其中包含item1、item2和item3
item1
test1
test2
item2
test3
test4
item3
test5
superItem
我应该使用哪些方法来获得以下结果; 我得到了一个变量check,它包含test1 我想在result变量item1中接收。。。你知道吗
check
result
换句话说: 我想接收与变量check中包含相同文本的项的名称
最好的解决方案是什么?你知道吗
我使用列表理解的实现。列表名('itemn')存储在superItem dict中,因此您可以在需要时获取它。你知道吗
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
我假设您将在字典中保存这些变量,如下面的代码所示。你知道吗
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
编辑
我为您添加了集合-您可以使用{ }作为它们。你知道吗
{ }
使用字符串项和列表理解的简单版本:
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"]]
我使用列表理解的实现。列表名('itemn')存储在superItem dict中,因此您可以在需要时获取它。你知道吗
性能测试:
我假设您将在字典中保存这些变量,如下面的代码所示。你知道吗
编辑
我为您添加了集合-您可以使用
{ }
作为它们。你知道吗使用字符串项和列表理解的简单版本:
相关问题 更多 >
编程相关推荐