我有一份表格清单 -
a_list = [[1, [2, 3, 4]], [2, [3, 4]], [3, [4]]]
我想将其转换为表单 -
b_list = [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
使用列表理解,我尝试使用下面的代码
for lst in tup:
for lst1 in tup[1]:
tup2 = [lst[0],lst1]
得到(这是错误的) -
tup2 = [3, [3, 4]]
请帮助,提前致谢
答案 0 :(得分:3)
与列表理解相关:
a_list = [[1, [2, 3, 4]], [2, [3, 4]], [3, [4]]]
b_list = [[x,y] for [x,b] in a_list for y in b]
print(b_list)
结果:
[[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]
使用[x,b]
将商品解包为x
作为号码,b
作为您的列表。循环遍历b
的元素并构建平面风格的情侣。
答案 1 :(得分:-1)
无论有多少int,你都可以尝试这样的事情:
for sub_list in b:
for items in sub_list:
if isinstance(items, list):
track = sub_list.index(items)
first = sub_list[:track]
second = sub_list[track:][0]
import itertools
print([list(k) for k in itertools.product(first, second)])
测试用例:
b = [[1, [2, 3, 4]], [2, [3, 4]], [3, [4]]]
输出:
[[1, 2], [1, 3], [1, 4]]
[[2, 3], [2, 4]]
[[3, 4]]
测试用例2:
b=[[1,2,[2, 3, 4]], [2,3,5,6 ,[3, 4]], [3, [4]]]
输出:
[[1, 2], [1, 3], [1, 4], [2, 2], [2, 3], [2, 4]]
[[2, 3], [2, 4], [3, 3], [3, 4], [5, 3], [5, 4], [6, 3], [6, 4]]
[[3, 4]]