我有两个元组列表,格式都是(integer, string)
第一个列表是第二个列表的子集,我只希望第二个列表的元素与第一个列表共享一个整数。例如
清单1:
int string
==============
1 string1
3 string2
5 string3
清单2:
int string
===================
1 otherstring1
2 otherstring2
3 otherstring3
4 otherstring4
5 otherstring5
我希望我的结果是
int string
===================
1 otherstring1
3 otherstring3
5 otherstring5
有没有办法使用IN
关键字来实现这一点?使用python3.7
初始Anwser:
将set用于哈希有效性:
假设这两个列表是
list1
和list2
。我们首先从list1
中提取整数:这里使用
{
和}
来创建一个集合而不是一个列表(因为在集合中查找比在列表中查找更快)然后循环
list2
中的项,只保留编号在integers
中的字符串:创建一组出现在列表1中的整数:
那你就可以了
为什么是一套?
由于集合提供了O(1)查找,通过使用集合,我们得到了时间复杂度为O(n)而不是O(n^2)的解
完整示例:
输出
相关问题 更多 >
编程相关推荐