将一个列表与另一个嵌套列表(无序)进行比较并输出lis

2024-05-29 01:48:39 发布

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

以下是我的清单:

x = [['Godel Escher Bach', '1979', 'Douglas Hofstadter'], ['What if?', '2014', 'Randall Munroe'], ['Thing Explainer', '2015', 'Randall Munroe'], ['Alan Turing: The Enigma', '2014', 'Andrew Hodge']]
y = ['2014', '2015', '2014']

例如,取y[0]并将其与x[0][0]~x[2][2]进行比较,然后打印x中包含y元素的列表(嵌套列表)

此函数应将y中的所有元素与x中的每个元素进行比较

我已经想了两天了,我想不出来。请帮帮我!你知道吗


Tags: 元素列表ifwhatthingdouglasalanescher
3条回答

您可以使用内置的filter方法筛选所需内容:

>>> filter(lambda s: s[1] in y, x)
[['What if?', '2014', 'Randall Munroe'], ['Thing Explainer', '2015', 'Randall Munroe'], ['Alan Turing: The Enigma', '2014', 'Andrew Hodge']]

它的功能:

它遍历x列表中的每个列表,并使用lambda函数检查是否在y[1]中找到每个子列表的第二个元素

编辑:

如果您确定x的每个子列表中的日期保持相同的索引,即s[1],则上述代码将起作用

但如果您不能保证,那么我更喜欢下一个代码(我已经向x添加了其他元素,具有不同的日期索引:

>>> z = [['Godel Escher Bach', '1979', 'Douglas Hofstadter'], ['What if?', '2014', 'Randall Munroe'], ['Thing Explainer', '2015', 'Randall Munroe'], ['Alan Turing: The Enigma', '2014', 'Andrew Hodge'],['2015','Thing Explainer',  'Randall Munroe'], ['Alan Turing: The Enigma', 'Andrew Hodge','2014']]
>>> 
>>> 
>>> filter(lambda s: set(s).intersection(y), z)
[['What if?', '2014', 'Randall Munroe'], ['Thing Explainer', '2015', 'Randall Munroe'], ['Alan Turing: The Enigma', '2014', 'Andrew Hodge'], ['2015', 'Thing Explainer', 'Randall Munroe'], ['Alan Turing: The Enigma', 'Andrew Hodge', '2014']]

据我所知,你想列一张在x出版日期在y的书的清单。这应该做到:

>>> [b for b in x if b[1] in y]

[['What if?', '2014', 'Randall Munroe'],
 ['Thing Explainer', '2015', 'Randall Munroe'],
 ['Alan Turing: The Enigma', '2014', 'Andrew Hodge']]

y可能应该是这里的set。性能提升可以忽略不计,因为y非常小,但作为一个集合,它传达了您打算如何使用它:

years = {'2014', '2015', '2014'}

最后,您可能希望使用来自collectionsnamedtuple来表示您的书籍。比如:

from collections import namedtuple
Book = namedtuple('Book', 'name year author')
books = [Book(b) for b in x]

然后,上面的列表变成:

[b for b in books if b.year in years]

这是好的和可读的。你知道吗

使用列表理解:

list(i for i in x if y[0] in i)

>>> [['What if?', '2014', 'Randall Munroe'], ['Alan Turing: The Enigma', '2014', 'Andrew Hodge']]

相关问题 更多 >

    热门问题