如何在Python列表集合中查找目标列表并筛选出现次数最多项
问题需求
用6元素的listB在listA中查找匹配项:
listA的元素是7元素列表,最后一个元素是up或down后缀,每个元素附带出现次数- 匹配规则:
listA元素的前6个元素和listB完全一致 - 若存在多个匹配项,筛选出出现次数最多的那个
数据A收集代码
for i in range(len(fsa)): if fsa[i] < fsb[i]: kol.append('1') else: kol.append('0') start = 0 end = len(fsa) j = [ ] for x in range(start, end, 6): m = fsb[x:x+6] t = kol[x:x+6] if m[0] < m[-1]: t.append('up') else: t.append('down') j.append(t) counter = Counter(tuple(j) for j in j) for members, count, in counter.items(): print(list(members), count)
数据A输出
['1', '1', '0', '1', '0', '1', 'down'] 2 ['0', '0', '1', '1', '1', '1', 'up'] 2 ['1', '0', '0', '1', '0', '1', 'up'] 1 ['0', '0', '0', '1', '1', '0', 'up'] 2 ['1', '1', '0', '0', '0', '0', 'up'] 1 ['0', '0', '1', '1', '0', '1', 'down'] 1 ['1', '0', '0', '0', '0', '1', 'down'] 1 ['1', '1', '1', '1', '1', '1', 'up'] 1
数据B收集代码
for _ in range(num): inner = driver.find_element_by_xpath("//html/body/div[1]/div[2]/div/div/div/div[2]/div/div[2]/div[2]/div/div/div[2]/div[4]/span[1]").get_attribute("innerHTML") print(inner) lok.append(inner) time.sleep(20)#the hour print(lok) lokk = [] num = 7 for _ in range(num): inner = driver.find_element_by_xpath("//html/body/div[1]/div[2]/div/div/div/div[2]/div/div[2]/div[2]/div/div/div[2]/div[4]/span[1]").get_attribute("innerHTML") print(inner) lokk.append(inner) time.sleep(20) print(lokk)
数据B输出
listB = ['1', '1', '1', '1', '1', '1']
解决方案代码
from collections import Counter # 存储匹配到的项(次数 + 完整列表) matched_items = [] for item_tuple, count in counter.items(): item_list = list(item_tuple) # 对比前6个元素是否和listB一致 if item_list[:6] == listB: matched_items.append( (count, item_list) ) if not matched_items: print("没有找到匹配项") else: # 按出现次数降序排序,取第一个就是次数最多的 matched_items.sort(reverse=True, key=lambda x: x[0]) max_count, best_match = matched_items[0] print(f"匹配到次数最多的项: {best_match},出现次数: {max_count}")
代码说明
- 遍历
counter中的每一项,提取列表前6个元素和listB对比,匹配项存入matched_items - 若
matched_items为空,说明无匹配结果 - 对匹配项按次数降序排序,第一个元素即为次数最多的目标项
针对示例中的listB,运行后会输出:
匹配到次数最多的项: ['1', '1', '1', '1', '1', '1', 'up'],出现次数: 1
内容的提问来源于stack exchange,提问作者user 456354
相关产品推荐
相关产品推荐

