修剪空间并在Python中加入列表



我是Python的新手,我试图通过消除空间并合并列表来获得最终列表。让我们考虑一下我有两个列表。

list1 = ['string1,1, 2','string2,2,3','string3,3,4']
list2 = ['string1 ,  5, 6','string2 ,  6, 7', 'string3,  8, 9']

我的最终列表应该像下面的那样,消除列表2中的元素之前的空间并与list1。

list = ['string1,1,2,5,6','string2,2,3,6,7','string3,3,4,8,9']

有什么方法可以实现这一目标?我疲倦了下面的东西,但没有工作

list2 = [x for x in list2 if x.strip()]
list = list1+list2
#replacing whitespaces
l1 = [x.replace(' ', '') for x in list1]
l2 = [x.replace(' ', '') for x in list2]
#returns a dictionary of items in list, for 'string1,2,3' key=string1, values=[2, 3]
def func(l):
     d = {}
     for i in l:
             d[i.split(',')[0]] = i.split(',')[1:]
     return d
l2_dict = func(l2)
#list with elements key corresponding to l1's key
l2_1 = [','.join(l2_dict[i.split(',')[0]]) if i.split(',')[0] in l2_dict else '' for i in l1]
result = [i + ',' + j for i,j in zip(l1, l2_1)]

即使我们重新排序list2元素,上面也可以工作。

输出:

['string1,1,2,5,6', 'string2,2,3,6,7', 'string3,3,4,8,9']
list1 = ['string1,1, 2','string2,2,3','string3,3,4']
list2 = ['string1 ,  5, 6','string2 ,  6, 7', 'string3,  8, 9']
res =[]
for i, j in zip(list1,list2):
    tmp =  []
    tmp1 = [l.strip() for l in i.split(',')]
    tmp2=[l.strip() for l in j.split(',')]
    for k in tmp1:
        if k not in tmp:
            tmp.append(k.strip())
    for k in tmp2:
        if k not in tmp:
            tmp.append(k.strip())
    res.append(','.join(tmp))
print(res)

输出

['string1,1,2,5,6', 'string2,2,3,6,7', 'string3,3,4,8,9']

我认为您需要:

new_list = []
for i in list1:
  for j in list2:
    # remove the spaces
    x = i.replace(" ","").split(",")
    y = j.replace(" ","").split(",")
    # check if 1st element is same or not
    if x[0] == y[0]:
      result = ",".join(x+y[1:])
      new_list.append(result)
print(new_list)

输出:

['string1,1,2,5,6', 'string2,2,3,6,7', 'string3,3,4,8,9']

strip((只能从字符串中删除前导空间和尾随空间。如果要从字符串中删除所有空格,则可以使用String.Replace(","(,并且您的列表综合是不正确的。总体而言,要删除空间,您需要这样做:

list2 = [x.replace(","(在list2中的x]

list1 = [x.replace(","(在list1中的x]

有关详细信息,请阅读:列表的理解有关添加/合并两个列表的问题的其余部分尚不完全清楚。假设您将合并并删除重复术语,然后使用KNH190评论中的代码:

res = [','.join(x.split(',') + y.split(',')[1:]) for x,y in zip(list1, list2)]

最新更新