使用IN关键字比较两个元组列表

2024-09-30 10:31:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个元组列表,格式都是(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


Tags: 元素列表string格式整数integer子集int
3条回答

初始Anwser:

output = [a,b for a,b in list_2 if a in [a for a,b in list_1]]

将set用于哈希有效性:

output = [a,b for a,b in list_2 if a in set([a for a,b in list_1])]

假设这两个列表是list1list2。我们首先从list1中提取整数:

integers = {x for x,y in list1}

这里使用{}来创建一个集合而不是一个列表(因为在集合中查找比在列表中查找更快)

然后循环list2中的项,只保留编号在integers中的字符串:

strings = [y for x,y in list2 if x in integers]

创建一组出现在列表1中的整数:

integers_in_list_one = {tup[0] for tup in list1}

那你就可以了

common = [tup for tup in list2 if tup[0] in integers_in_list_one]

为什么是一套?

由于集合提供了O(1)查找,通过使用集合,我们得到了时间复杂度为O(n)而不是O(n^2)的解

完整示例:

list_1 = [(1, 'string1'), (3, 'string2'), (5, 'string3')]
list_2 = [(1, 'otherstring1'), (2, 'otherstring2'), (3, 'otherstring3'), (4, 'otherstring4'), (5, 'otherstring5')]

integers_in_list_one = {tup[0] for tup in list_1}
common = [tup for tup in list_2 if tup[0] in integers_in_list_one]
print(common)

输出

[(1, 'otherstring1'), (3, 'otherstring3'), (5, 'otherstring5')]

相关问题 更多 >

    热门问题