我在两个列表之间进行迭代以查看其中一个列表是否包含另一个列表的元素时遇到问题。在其中一个列表中,我还有另一个列表。有时这个列表只有字符串,有时是字符串和..另一个列表。
所以问题就在这里。如果它只有字符串,我想知道这些字符串的 ALL
是否都在 Mainlist
内。
但是,如果我有 srtings AND
另一个列表..我想知道列表之外的ALL
字符串是否都在 Mainlist
并且如果列表中的AT LEAST ONE
字符串位于Mainlist
中。
所以,假设我有一个主列表:
主列表 = ['AA', 'BB', 'CC', 'DD', 'EE', 'FF']
现在,我有其他列表想要迭代此 Mainlist
:
list1 = [['AA', ['BB', 'YY']], ['AA', 'GG']]
在 list1
上,我有两个列表:['AA', ['BB', 'YY']]
和 ['AA', 'GG ']
一个只有字符串,另一个有字符串和另一个列表。
现在我需要知道 list1
上的元素是否在 Mainlist
上,并获取 list1
中给我的元素的索引正确
结果。
在这种情况下,在索引 0
处它会是True
。因为 Mainlist
包含项目 'AA'
和 'BB'
。
其他示例:
list2 = [['AA', 'JJ'], ['EE', 'FF']] # False at index 0 = Mainlist does not have 'JJ' / True at index 1 = Mainlist has 'EE' and 'FF'
list3 = [['AA', 'KK', ['BB', 'CC']], ['JJ', 'GG']] # False at index 0 item 'KK' is not in Mainlist / False at index 1 = Mainlist does not have 'JJ' and 'GG'
list4 = [['EE', 'FF', "OO"], ['AA', 'BB', 'CC',['DD', 'MM']], ['GG', ['BB', 'CC', 'DD']]] #False at index 0 = Mainlist does not have 'OO' / True at index 1 = Even if 'MM' is not in Mainlist, 'DD' is. / False at index 2 = 'GG' is not in Mainlist
我在尝试实现这一目标时感到头疼..有没有人有提示可以帮助我解决这个问题? 提前致谢
最佳答案
你可以尝试这个,返回一个包含每个索引及其各自 bool 值的字典:
list2 = [['AA', 'JJ'], ['EE', 'FF']] # False at index 0 = Mainlist does not have 'JJ' / True at index 1 = Mainlist has 'EE' and 'FF'
list3 = [['AA', 'KK', ['BB', 'CC']], ['JJ', 'GG']] # False at index 0 item 'KK' is not in Mainlist / False at index 1 = Mainlist does not have 'JJ' and 'GG'
list4 = [['EE', 'FF', "OO"], ['AA', 'BB', 'CC',['DD', 'MM']], ['GG', ['BB', 'CC', 'DD']]] #False at index 0 = Mainlist
Mainlist = ['AA', 'BB', 'CC', 'DD', 'EE', 'FF']
def func(ls):
dct={}
for idx,l in enumerate(ls):
if all(isinstance(elem, str) for elem in l):
dct.update({idx:all(elem in Mainlist for elem in l)})
else:
cond=all(el in Mainlist for el in [i for i in l if isinstance(i, str)]) and any(ele in Mainlist for el in [i for i in l if isinstance(i, list)] for ele in el)
dct.update({idx:cond})
return dct
print(func(list2))
print(func(list3))
print(func(list4))
输出:
{0: False, 1: True}
{0: False, 1: False}
{0: False, 1: True, 2: False}
关于python - 在其他列表中迭代 python 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62583217/