我有一个包含3个子元组列表的列表,如
[[(['A', 'B', 'A'], ['B', 'O', 'A']),
(['A', 'B', 'A'], ['B', 'A', 'O']),
(['A', 'B', 'O'], ['B', 'O', 'A']),
(['A', 'B', 'O'], ['B', 'A', 'O']),
(['A', 'B', 'A'], ['B', 'O', 'A']),
(['A', 'B', 'A'], ['B', 'A', 'O'])],
[(['A', 'B', 'A'], ['B', 'A', 'A']),
(['A', 'B', 'O'], ['B', 'A', 'A']),
(['A', 'B', 'A'], ['B', 'A', 'A'])],
[['A', 'B', 'A'], ['A', 'B', 'O']],
[['A', 'B', 'B']],
[['B', 'A', 'A']]]
假设list2 = ['A', 'B', 'A'].
我的目标是获得list1
中包含元组list2
的任何元组对(或元组的单态集)的索引列表。我尝试按如下方式使用enumerate
函数,但结果不正确
print([i for i, j in enumerate(bigset) if ['A', 'B', 'A'] in j[0] or
['A', 'B', 'A'] == j[0] or [['A', 'B', 'A']] in j[0]])
有人能帮我解决这个问题吗?由于list1
中出现的元组的不同大小的不匹配,我非常困惑
我的另一个问题是:我想在list1
中找到三元素列表的总数。因此,如果我用手来做,答案是22
。但是如何在代码中实现呢?我想我们需要使用两个for
循环
预期输出对于上面的list1
和给定的list2
,我们将得到包含list2
的索引列表是[0,1,5,6,7,9,10]
好的,给你
这将使用递归,因为我们不知道
list1
的深度,所以索引将按如下方式计算:等等。。。(与您在一行中书写的顺序相同)
结果如下:
现在是代码
s
是我们正在研究的索引count
是元素(22)的总量。Indexes
是您想要的索引列表这项工作即使你做了一个
list3 = [list1,list1,[list1,[list1],list1]]
,你也可能想试试祝你好运,现在结束你的脚本
如果我们先将列表1整理成更友好的格式,对您的实现有用吗?如果是这样的话,你可以用一种非常简单的方式:
检查list1的每个元素,如果元素本身是一个元组的大列表,那么我们希望进一步解包。如果该元素是一个元组(因此该元组的第一个元素是一个列表),或者它本身就是一个3元素列表,那么我们只想按原样附加它
然后,您可以更轻松地搜索索引:
对于您关于查找有多少个3元素列表的问题,如果不是特别优雅的解决方案,可以使用For循环:
编辑:为了回答您在评论中提出的关于
for n in nice_list
部分如何工作的问题,只需迭代列表中的每个元素。要探索这一点,请尝试编写一些代码来打印nice_list[0]
、nice_list[1]
等,或者编写一个for循环来打印每个n
,这样您就可以看到它是什么样子了。例如,您可以执行以下操作:去了解它是如何工作的
由于深度未知和/或缺少已知的阵列展平操作,这种方法有点非常规-我会尝试使用正则表达式:
这将产生:
(我相信这就是你想要的实际结果)
相关问题 更多 >
编程相关推荐