提问人:Deltag0ny 提问时间:10/6/2022 更新时间:10/6/2022 访问量:75
有没有办法在包含不同类型的嵌套列表的单个列表上使用列表推导
Is there a way to use list comprehension on a single list containing different types of nested lists
问:
我理解嵌套列表推导,但搜索了一下是否可以使用嵌套列表推导将列表分隔成这样的单个项目:我在网上没有找到任何关于它的内容。list1 = [ [1,2,3], [10,11,12], [100,111,112], [1, 10, 11, [1000101]]]
这是我的想法:
def foo(x):
for a in x:
for b in a:
if type(b) != list:
unpacked = [b for a in x for b in a]
if type(b) == list:
unpacked.append(*b)
return unpacked
但是,输出是这样的:[1, 2, 3, 10, 11, 12, 100, 111, 112, 1, 10, 11, [1000101], 1000101]
答:
0赞
Gabriel Flores
10/6/2022
#1
像这样的东西?
def foo(x):
unpacked = []
for a in x:
unpacked.extend(
[b for b in a]
)
return unpacked
list1 = [ [1,2,3], [10,11,12], [100,111,112], [1, 10, 11, [1000101]]]
print(foo(list1))
0赞
freemangifts
10/6/2022
#2
试试这个:
def unpacklist(list):
alist = []
a = 0
for sublist in list:
try:
for i in sublist:
alist.append(i)
except TypeError:
alist.append(sublist)
for i in alist:
if type(i) == type([]):
a += 1
break
if a == 1:
return unpacklist(alist)
if a == 0:
return alist
list = [ [1,2,3], [10,11,12], [100,111,112], [1, 10, 11, [1000101]]]
a = unpacklist(list)
print(a)
评论
0赞
Deltag0ny
10/8/2022
这是一种方法,但它不使用列表推导。不过还是不错的
评论