【问题标题】:How to determine what list a subset is a part of and print the name?如何确定子集属于哪个列表并打印名称?
【发布时间】:2021-05-19 15:23:10
【问题描述】:

我想确定是否可以在 python 中的 list 中的嵌套集中找到字符串列表,并打印找到它的列表或列表集。

例如:

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]

我的尝试要么失败,要么得到:

['鬣蜥','猫','蜘蛛','猴子','狗']

这是动物数组,但我只想要术语动物和颜色。

有没有办法搜索嵌套列表并打印它是哪个列表的一部分?

【问题讨论】:

  • 在你的“打印”中你应该使用type而不是list2[type]。请注意,缺少一堆 : 并且使用 type 作为变量名是很差的,因为它会使 type(list1) 不起作用。您的打印也不是有效的打印声明:-)
  • 我想我已经编辑了这个问题,以消除您可能遇到的任何困惑。如果我需要更多解释,请告诉我。

标签: python-3.x list search nested set


【解决方案1】:

您可能不想在代码中使用构成变量名称的实际字符。因此,您需要明确定义每个列表的类别:

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 somewhere 的每个成员的匹配项。

【讨论】:

  • 工作得很好,差点忘了在动物列表中添加“动物”标签。它使用这段代码准确地打印出我想要的内容。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-03
  • 2022-06-17
  • 2023-03-13
  • 1970-01-01
  • 2021-08-10
相关资源
最近更新 更多