python - 找出一个元组是否包含在另一个在 Python 中重复的元组中
问题描述
Tuple1 = (1,2,2)
TupleList = [(1,2,3), (1,2,3,2)]
我想在TupleList中搜索作为Tuple1超集的任何元组。结果应该是在这种情况下:
(1,2,3,2)
但是如果我使用 .issuperset() 函数,它不会考虑到Tuple1中 2 的重复。
如何解决这个问题呢?
解决方案
如果您需要考虑元素频率,这可能是该实用程序的一个很好的collections.Counter
用途。
from collections import Counter
tuple_1 = (1, 2, 2)
tuple_list = [(1, 2, 3), (3, 4, 1), (1, 2, 3, 2)]
def find_superset(source, targets):
source_counter = Counter(source)
for target in targets:
target_counter = Counter(target)
if is_superset(source_counter, target_counter):
return target
return None # no superset found
def is_superset(source_counter, target_counter):
for key in source_counter:
if not target_counter[key] >= source_counter[key]:
return False
return True
print(find_superset(tuple_1, tuple_list))
输出:
(1, 2, 3, 2)
推荐阅读
- react-native - 在调用函数 React-Native 上保存 textInputs 的值
- javascript - 将日期和时间保存为按钮的值
- django - Rest API 参数为空 Serializer 没有模型
- php - 如何在 Symfony/Doctrine 中为 FileType 的输入设置默认值?
- git - 本地中央 git 存储库的离线同步
- c# - Xamarin.Forms 应用程序中的试用版
- azure-data-explorer - 如何有条件地强制 Kusto 中的查询失败
- r - 使用 R 仅选择一列批量处理多个 .csv 文件
- php - 致命错误:未捕获的错误:()中未找到类“电报”
- c++ - 使用 glm 的旋转功能时,预期的旋转方向是什么?