假设我有以下两个列表:
a = ['hello ', 'goodbye ']
b = ['tom', 'dick', 'harry']
我想创建两个新的列表,如下所示:
['hello tom', 'hello dick', 'hello harry']
['goodbye tom', 'goodbye dick', 'goodbye harry']
最狡猾的方式是什么?我的猜测是有比嵌套循环更优雅和高效的东西,但考虑到a或b可能是不同的大小,这是否需要字典?
答案 0 :(得分:4)
您可以在nested list comprehension中生成这些内容:
[['{} {}'.format(greeting, name) for name in b] for greeting in a]
生成列表:
>>> a = ['hello ', 'goodbye ']
>>> b = ['tom', 'dick', 'harry']
>>> [['{} {}'.format(greeting, name) for name in b] for greeting in a]
[['hello tom', 'hello dick', 'hello harry'], ['goodbye tom', 'goodbye dick', 'goodbye harry']]