通过添加列表元素来创建新列表

时间:2015-12-05 17:45:54

标签: python list

假设我有以下两个列表:

a = ['hello ', 'goodbye ']
b = ['tom', 'dick', 'harry']

我想创建两个新的列表,如下所示:

['hello tom', 'hello dick', 'hello harry']
['goodbye tom', 'goodbye dick', 'goodbye harry']

最狡猾的方式是什么?我的猜测是有比嵌套循环更优雅和高效的东西,但考虑到a或b可能是不同的大小,这是否需要字典?

1 个答案:

答案 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']]