[英]Comparing a list against a tuple
我正在尝试将值列表与tuples
list
进行比较。 例如:
list = [1.0, 2.0]
list_of_tuples = [(3, 1.0, 'a'), (4, 2.0, 'b'), (5, 3.0, 'c')]
理想情况下,我想做的是获取元组列表,并检查该列表中的所有值是否在另一个列表中存在。 在示例列表的情况下,存在我提供的1.0和2.0以上的内容,但没有提供3.0。 另一个问题是,在进行理解时,元组列表中值的位置将是未知的(在我上面提供的示例中不是这种情况),因此我实际上不确定是否可以做我想做的事。
任何帮助,将不胜感激,或者替代解决方案也将是有帮助的。
如果只有一个元组的值必须在list
,那么这应该给你的元组这是无效的名单。
filter(lambda values: not any(value in list for value in values), list_of_tuples)
否则,如果所有值都必须在列表中
filter(lambda values: not all(value in list for value in values), list_of_tuples)
flt=[]
for tup in list_of_tuples:
flt.extend(tup)
for val in lst:
if val in flt:
print val
else:
print 'failed'
另外,切勿使用内置名称调用var。 称它为lst
,而不是list
这是一种递归搜索算法,该算法将返回一个索引列表,您可以在该列表中恢复找到的值(地址从右到左读取。可能有一种在另一个方向附加它们的方法):
def recursive_search(searchable, value):
address = []
if _recursive_search(searchable, value, address):
return address
else:
raise Exception("Value not found!")
def _recursive_search(searchable, value, address):
if hasattr(searchable, '__iter__'): # check if searchable is a list or a tuple
for i in range(len(searchable)):
if _recursive_search(searchable[i], value, address):
address.append(i)
return True
else:
return False
else:
if searchable == value:
return True
#recursive_search([[[1,2],[3,4],[5,6]],[[7,8],[9,10],[11,12]]], 11) -> [0,2,1]
编辑如果要在值列表上应用它,可以使用map
或类似的方法。 map(lambda x: recursive_search(list_of_tuples, x), list)
编辑如果您还想搜索其他方向(似乎您在问题中所做的那样),则可以将递归映射函数与recursive_search
结合使用...
def recursive_map(some_func, thing_to_map_over):
some_func = some_func or recursive_map
if hasattr(thing_to_map_over, '__iter__'):
return map(lambda x: recursive_map(some_func, x), thing_to_map_over)
else:
return some_func(thing_to_map_over)
因此recursive_map(lambda x: recursive_search(list, x), list_of_tuples)
会告诉您list_of_tuples
中的所有内容是否都在list中以及这些内容的位置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.