如何解决包含某些元组的元组的元组索引列表
我有一个元组的3个子列表的列表list1
[[(['A','B','A'],['B','O','A']),(['A','A','O']),'O'],'O'])],[(['A','A'])],[['A',['A','O']],'B']],[['B','A']]]
假设list2 = ['A','A'].
我的目标是获取包含元组{{的list1
中任何成对的元组(或单例元组)的索引列表 1}}。我尝试如下使用list2
函数,但结果不正确
enumerate
有人可以帮助我解决这个问题吗?由于print([i for i,j in enumerate(bigset) if ['A','A'] in j[0] or
['A','A'] == j[0] or [['A','A']] in j[0]])
中出现的元组的大小不同,元组不匹配,我感到非常困惑。
我还有一个问题:我想在list1
中找到三元素列表总数。因此,如果我手工完成,答案是list1
。但是,如何在代码中做到这一点呢?我猜我们需要使用两个22
循环吗?
预期输出对于上面的for
,使用给定的list1
,我们将得到包含list2
的索引列表为list2
。>
解决方法
如果我们首先将您的list1整理成更友好的格式,对您的实现是否可行?如果是这样,您可以用一种非常简单的方式做到这一点:
遍历list1的每个元素,如果该元素本身是一个很大的元组列表,那么我们想进一步解压缩。如果该元素是一个元组(因此该元组的第一个元素是一个列表),或者它本身是您的3元素列表中的一个,那么我们只想按原样追加它。
nice_list = []
for i in list1:
if type(i[0]) == str or type(i[0]) == list:
# i.e. i is one of your 3-element lists,or a tuple of lists
nice_list.append(i)
else:
#If i is still a big list of other tuples,we want to unpack further
for j in i:
nice_list.append(j)
然后,您可以更轻松地搜索索引:
for i,idx in zip(nice_list,range(len(nice_list))):
if ['A','B','A'] in i:
print(idx) #Or append them to a list,whatever you wanted to do
对于您关于找到多少个3元素列表的问题的解决方案,它不是特别优雅,可以使用for循环:
no_of_lists = 0
for n in nice_list:
if type(n) == tuple:
no_of_lists += len(n)
elif type(n) == list and type(n[0]) == list:
# if it is a list of lists
no_of_lists += len(n)
elif type(n) == list and type(n[0]) == str:
#if it is a 3-element list
no_of_lists_lists += 1
print('Number of 3-element lists contained:',no_of_lists)
编辑:要回答您在评论中询问的for n in nice_list
部分如何工作的问题,这只是遍历列表的每个元素。要对此进行探索,请尝试编写一些代码以打印出nice_list[0]
,nice_list[1]
等,或者通过一个for循环来打印出每个n
,以便您可以看到类似的内容。例如,您可以这样做:
for n in nice_list:
print(n)
了解其工作原理。
,由于深度未知和/或缺乏已知的数组展平操作,因此采用了略微非常规的方法-我会尝试使用regex:
import re
def getPos(el,arr):
el=re.escape(str(el))
el=f"(\({el})|({el}\))"
i=0
for s in re.finditer(r"\([^\)]+\)",str(arr)):
if(re.match(el,s.group(0))):
yield i
i+=1
哪个产量:
>>> print(list(getPos(list2,list1)))
[0,1,4,5,6,8,9]
(我相信这是您想要的实际结果)。
,好,那么你去
之所以使用递归,是因为我们不知道您的list1
的深度,因此索引将像这样计算:
0,1
2,3,7
8,9,10,11,12
等...(与第一行相同的顺序)
结果将是:
[0,2,12,16,18]
现在输入代码
def foo(l,ref):
global s
global indexes
for items in l: #if it's an element of 3 letters
if len(items)== 3 and len(items[0])==1:
if items == ref:
indexes.append(s) #save his index if it match the ref
s+= 1 #next index
else: #We need to go deeper
foo(items,ref)
return(s)
list1 = [[(['A','A'],['B','O','A']),(['A','A','O']),'O'],'O'])],[(['A','A'])],[['A',['A','O']],'B']],[['B','A']]]
list2 = ['A','A']
indexes = []
s=0
count= foo(list1,list2)
print(indexes)
s
是我们正在处理的索引
count
是元素(22)的总数。
Indexes
是您想要的索引列表。
即使您进行list3 = [list1,list1,[list1,[list1],list1]]
的这项工作,也可能要尝试一下。
最幸运的是现在结束脚本。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。