这是我的列表:
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 中的每个元素进行比较
我想了两天了,还是想不出来。请帮忙!
最佳答案
据我了解,您希望列出 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'}
最后,您可能希望使用 collections
中的 namedtuple
来表示您的图书。像这样的东西:
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]
这很好并且可读。
关于python - 将列表与另一个嵌套列表(无序)进行比较并输出列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34056544/