我是python的新手,我试图通过消除空格并合并列表来获得最终列表。 让我们考虑一下我有两个列表。
list1 = ['string1,1, 2','string2,2,3','string3,3,4']
list2 = ['string1 , 5, 6','string2 , 6, 7', 'string3, 8, 9']
我的最终列表应类似于以下内容,方法是消除list2中元素之前的空格并与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
答案 0 :(得分:2)
#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']
答案 1 :(得分:1)
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']
答案 2 :(得分:1)
我认为您需要:
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']
答案 3 :(得分:0)
strip()只能从字符串中删除前导和尾随空格。如果要从字符串中删除所有空格,则可以使用string.replace(“”,“”),并且列表理解不正确。总体来说,删除空间需要这样做:
list2 = [x.replace(“”,“”)for list2中的x]
list1 = [x.replace(“”,“”)for list1中的x]
有关详细信息,请点击此处:list-comprehensions 有关添加/合并两个列表的问题的其余部分尚不十分清楚。假设您将合并并删除重复的术语,然后使用knh190的注释中的代码:
res = [','.join(x.split(',') + y.split(',')[1:]) for x,y in zip(list1, list2)]