如何确定子集属于哪个列表并打印名称?
How to determine what list a subset is a part of and print the name?
我想确定是否可以在 python 的列表中的嵌套集中找到字符串列表,并打印在其中找到的列表或列表集。
例如:
list1 = ['cat','red']
animal = ['iguana','cat','spider','monkey','dog']
color = ['yellow','red','blue','purple','green','orange']
action = ['run','jump','swim','fly']
list2 = [animal,color,action]
list1 = set(list1)
for category in list2
if list1.issubset(type)
print(list1, "is part of", category)
结果应该是:
['cat','red'] is a part of [animal,color]
我的尝试要么失败了,要么我得到:
['iguana','cat','spider','monkey','dog']
哪个是动物数组,但我只想用动物和颜色来代替。
有什么方法可以搜索嵌套列表并打印它所属的列表吗?
您可能不想在 代码中使用组成变量名称的实际字符 。因此,您需要明确定义每个列表的类别:
list1 = ['cat','red']
animal = ("animal", ['iguana','cat','spider','monkey','dog'])
color = ("color", ['yellow','red','blue','purple','green','orange'])
action = ("action", ['run','jump','swim','fly'])
list2 = [animal,color,action]
matches = []
for item in list1:
for category in list2:
if item in category[1]:
matches.append(category[0])
print(list1, "is part of", matches)
这里的一个先决条件是您保证在 list2
.
list1
某处 的每个成员找到一个匹配项
我想确定是否可以在 python 的列表中的嵌套集中找到字符串列表,并打印在其中找到的列表或列表集。
例如:
list1 = ['cat','red']
animal = ['iguana','cat','spider','monkey','dog']
color = ['yellow','red','blue','purple','green','orange']
action = ['run','jump','swim','fly']
list2 = [animal,color,action]
list1 = set(list1)
for category in list2
if list1.issubset(type)
print(list1, "is part of", category)
结果应该是:
['cat','red'] is a part of [animal,color]
我的尝试要么失败了,要么我得到:
['iguana','cat','spider','monkey','dog']
哪个是动物数组,但我只想用动物和颜色来代替。
有什么方法可以搜索嵌套列表并打印它所属的列表吗?
您可能不想在 代码中使用组成变量名称的实际字符 。因此,您需要明确定义每个列表的类别:
list1 = ['cat','red']
animal = ("animal", ['iguana','cat','spider','monkey','dog'])
color = ("color", ['yellow','red','blue','purple','green','orange'])
action = ("action", ['run','jump','swim','fly'])
list2 = [animal,color,action]
matches = []
for item in list1:
for category in list2:
if item in category[1]:
matches.append(category[0])
print(list1, "is part of", matches)
这里的一个先决条件是您保证在 list2
.
list1
某处 的每个成员找到一个匹配项