Python将单个字符串元素与多个字符串元素组合

时间:2020-01-14 12:57:08

标签: python-3.x

我有两个列表:

  • 此元素包含两个带有分层';'的字符串的元素。
new_lst = [
    '50% Polyester;50% Polyester;50% Polyester;50% Polioster;50% Poliestere',
    '50% Elastane;50% Elasthanne;50% Elasthan;50% Elastano;50% Elastan'
]
  • 第二个列表中只有一个元素带有相同的定界符';'
newSpecialComp = [
    'Back:;Dos:;Rockseite:;Parte trasera:;Schiena:'
]

我需要将第一个列表new_lst中的FIRST元素与第二个列表newSpecialComp中的第一个元素组合。

所需的输出是包含两个元素的列表,但首先是上述两个元素的组合。

Final_lst = [
    'Back: 50% Polyester;Dos: 50% Polyester;Rockseite: 50% Polyester;Parte trasera: 50% Polioster;Schiena: 50% Poliestere',
    '50% Elastane;50% Elasthanne;50% Elasthan;50% Elastano;50% Elastan'
]
for i, j in zip(newsetSpecialComp, new_lst):
        elem2 = ';'.join(map(lambda x:i+' '+x,j.split(';')))
        final_lst.append(elem2)
        print('Final_lst :', final_lst)

这是我尝试过的。输出接近但不理想:

Final_lst = [
    'Back: 50% Polyester;Back: 50% Polyester;Back: 50% Polyester;Back: 50% Polioster;Back: 50% Poliestere', 
    'Dos: 50% Elastane;Dos: 50% Elasthanne;Dos: 50% Elasthan;Dos: 50% Elastano;Dos: 50% Elastan'
]

1 个答案:

答案 0 :(得分:1)

我认为您缺少帮助您解决此问题的符号是zip()

new_lst = [
    '50% Polyester;50% Polyester;50% Polyester;50% Polioster;50% Poliestere',
    '50% Elastane;50% Elasthanne;50% Elasthan;50% Elastano;50% Elastan'
]
newSpecialComp = [
    'Back:;Dos:;Rockseite:;Parte trasera:;Schiena:'
]

finalList = new_lst.copy()

# Assuming len(newSpecialComp) <= len(new_lst)
for index, val in enumerate(newSpecialComp):
    finalList[index] = ';'.join(' '.join(x) for x in zip(val.split(';'), new_lst[index].split(';')))

print(*finalList, sep='\n')

输出:

Back: 50% Polyester;Dos: 50% Polyester;Rockseite: 50% Polyester;Parte trasera: 50% Polioster;Schiena: 50% Poliestere
50% Elastane;50% Elasthanne;50% Elasthan;50% Elastano;50% Elastan

---更详细的书写方式---

new_lst = [
    '50% Polyester;50% Polyester;50% Polyester;50% Polioster;50% Poliestere',
    '50% Elastane;50% Elasthanne;50% Elasthan;50% Elastano;50% Elastan'
]
newSpecialComp = [
    'Back:;Dos:;Rockseite:;Parte trasera:;Schiena:'
]

finalList = new_lst.copy()

# Assuming len(newSpecialComp) <= len(new_lst)
for index, val in enumerate(newSpecialComp):
    str1 = val.split(';')
    str2 = new_lst[index].split(';')
    combined_strings = [' '.join(x) for x in zip(str1, str2)]
    finalList[index] = ';'.join(combined_strings)

print(*finalList, sep='\n')