合并两个列表,删除空字符串 [英] merging two lists, removing empty strings

查看:93
本文介绍了合并两个列表,删除空字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对python的数据结构技巧有些陌生,我一直在努力解决一个简单的问题.

I'm a bit new to python's data structure tricks, and I've been struggling with a simple problem.

我有2个2d列表

L1=[[1, '', 3],[1, '', 3]...]
L2=[['',2,''],['',2,''].....]

我正在寻找一种简单的方法来合并两个列表,以使结果是以下形式的新2d列表:

I'm looking for a simple way to merge the two lists such that the result is a new 2d list in the form:

result=[[1,2,3],[1,2,3]....]

我尝试过

newestlist=[sum(x,[]) for x in zip(mylist, mylist2)]

但是会产生结果

badresult=[[1,'',3,'',2,'']....]

有没有一种方法可以做到这一点?

is there a way way to accomplish this?

推荐答案

如果任何数字为0,这将不起作用:

This doesn't work if any numbers are 0:

>>> [[x or y or 0 for x, y in zip(a, b)] for a, b in zip(L1, L2)]
[[1, 2, 3], [1, 2, 3]]

为了清楚起见,将理解分为for循环:

Breaking the comprehension into a for loop for clarity:

output = []
for a, b in zip(L1, L2):
    innerlist = []
    for x, y in zip(a, b):
        innerlist.append(x or y or 0)  # 1 or '' = 1; '' or 2 = 2; etc
    output.append(innerlist)

这篇关于合并两个列表,删除空字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆