I have a list similar to this …
lst1 = ['Description:Blah blah', 'heading1:blahblah','heading2:BlahBlah1',"P!XXXX1','EXPECTED: 3823',"P!XXXX2','EXPECTED: 3824',"P!XXXX3','EXPECTED: 3825']
I would somehow like to merge the elements that contain/Start with P! and EXPECTED.
I’ve tired multiple things
[ x+y for x,y in zip(lst1[0::2], lst1[1::2]) ]
but this doesn’t exclude the other unwanted elements.
Any suggestions
brass75
(Dan Shernicoff)
June 24, 2025, 1:07pm
2
In order to do this you need to zip the iterables containing the parts you need. You can do this with a separate comprehension for each:
(item for item in lst1 if item.startswith('P!'))
(item for item in lst1 if item.startswith('EXPECTED'))
Each of these Generator
comprehensions will give you the values you want. Once you have that you can zip
them together and get the list you want:
[x + y
for x, y in zip(
(item for item in lst1 if item.startswith('P!')),
(item for item in lst1 if item.startswith('EXPECTED'))
)
]
The above comprehension gives:
['P!XXXX1EXPECTED: 3823', 'P!XXXX2EXPECTED: 3824', 'P!XXXX3EXPECTED: 3825']
Thanks , that’s excellent. Is there a way that I can leave the other elements in the list untouched in the same positions ?
Stefan2
(Stefan)
June 24, 2025, 1:21pm
4
What’s the desired result?
brass75
(Dan Shernicoff)
June 24, 2025, 1:23pm
5
What do you mean? You’re not actually making any modification to the original list - you’re creating 4 new objects - 3 generators (well, 2 and a zip
object but IIRC that is a generator under the hood) and a list
. The original list is not changed.
I meant if it was possible to have the first 3 elements untouched and remain in the list or would i then have to merge them into the the new list ?
brass75
(Dan Shernicoff)
June 24, 2025, 1:27pm
7
Since this is a new list you would need to do that. But you can create that list and then extend
it with new list comprehension I gave you easily enough.