假设您有2个唯一值列表,那么如何创建具有每个值记录的列表/数据框/数组。
list_1 = [1, 2, 3, 4]
list_2 = ['one', 'two', 'three', 'four']
expected = [
[1, 'one'],
[2, 'one'],
[3, 'one'],
[4, 'one'],
...
[1, 'four'],
[2, 'four'],
[3, 'four'],
[4, 'four']
]
答案 0 :(得分:1)
您可以使用列表理解:
[[i,j] for i in list_1 for j in list_2]
输出:
[[1, 'one'],
[1, 'two'],
[1, 'three'],
[1, 'four'],
[2, 'one'],
[2, 'two'],
[2, 'three'],
[2, 'four'],
[3, 'one'],
[3, 'two'],
[3, 'three'],
[3, 'four'],
[4, 'one'],
[4, 'two'],
[4, 'three'],
[4, 'four']]
或者您可以使用itertools.product
来获取元组列表:
import itertools
list(itertools.product(list_1, list_2))
输出:
[(1, 'one'),
(1, 'two'),
(1, 'three'),
(1, 'four'),
(2, 'one'),
(2, 'two'),
(2, 'three'),
(2, 'four'),
(3, 'one'),
(3, 'two'),
(3, 'three'),
(3, 'four'),
(4, 'one'),
(4, 'two'),
(4, 'three'),
(4, 'four')]