以下是一个示例代码,用于遍历列表中的列表并计算与不同列表的匹配项数:
def count_matching_items(lst):
# 创建一个空字典来存储每个列表的匹配项数
matching_counts = {}
# 遍历列表中的每个子列表
for sublist in lst:
# 计算与不同列表的匹配项数
count = 0
for other_sublist in lst:
if sublist != other_sublist:
for item in sublist:
if item in other_sublist:
count += 1
# 将匹配项数存储到字典中
matching_counts[str(sublist)] = count
return matching_counts
# 示例列表
my_list = [[1, 2, 3], [2, 3, 4], [3, 4, 5]]
# 计算匹配项数
result = count_matching_items(my_list)
print(result)
运行以上代码将输出字典,其中键是列表的字符串表示,值是与不同列表的匹配项数。示例输出可能如下所示:
{'[1, 2, 3]': 3, '[2, 3, 4]': 3, '[3, 4, 5]': 3}
在这个示例中,每个子列表与其他两个子列表都有3个匹配项。
下一篇:遍历列表中的列表时出现问题