我知道有很多关于我如何压扁二维列表的帖子但是这个有点不同,因为它是二维和三维列表的混合:
items = [[255, 204, 204], ..., [255, 179, 179], [[250, 250, 250], ..., [220, 220, 220]]]
我希望此列表仅为二维:
items = [[255, 204, 204], ..., [255, 179, 179], [250, 250, 250], ..., [220, 220, 220]]
我尝试使用列表理解,但它没有正确地压缩列表:
flat_list = [item for items in l for item in items]
将混合维数阵列展平为二维数组的最佳方法是什么?
答案 0 :(得分:5)
old_list = [[255, 204, 204], [255, 179, 179], [['250, 250, 250'], ['220, 220, 220']]]
new_list = []
for i in old_list:
if isinstance(i[0], list):
for j in i:
new_list.append(j)
else:
new_list.append(i)
print new_list
输出结果为:
[[255, 204, 204], [255, 179, 179], ['250, 250, 250'], ['220, 220, 220']]
答案 1 :(得分:3)
您可以使用递归函数:
create function GetOnlyCharacters
(
@SearchVal varchar(8000)
) returns table as return
with MyValues as
(
select substring(@SearchVal, N, 1) as number
, t.N
from cteTally t
where N <= len(@SearchVal)
and substring(@SearchVal, N, 1) like '[a-z]'
)
select distinct NumValue = STUFF((select number + ''
from MyValues mv2
order by mv2.N
for xml path('')), 1, 0, '')
from MyValues mv
演示:
def flatten(items):
for item in items:
if isinstance(item[0], list):
yield from flatten(item)
else:
yield item
答案 2 :(得分:1)
from itertools import chain
items = [[255, 204, 204], [255, 179, 179], [['250, 250, 250'], ['220, 220, 220']]]
flat_list = list(chain.from_iterable(lst if isinstance(lst[0], list) else [lst] for lst in items))
print(flat_list)
>>> [[255, 204, 204], [255, 179, 179], ['250, 250, 250'], ['220, 220, 220']]
答案 3 :(得分:0)
def tree2matrix(T):
if T == []:
return []
elif type(T) is not list:
return [[T]]
elif type(T[0]) is not list:
return [T]
else:
return tree2matrix(T[0]) + tree2matrix(T[1:])
X = [[255, 204, 204], [255, 179, 179], [['250, 250, 250'], ['220, 220, 220']]]
print(tree2matrix(X))