Home > front end >  Python List content stripping
Python List content stripping

Time:02-04

So, I have a list having string such as

matches=['A vs B','C vs D','E vs F','G vs H']

I want to get strip the list contents in such a way that I get two more lists of

t1=[A,C,E,G]
t2=[B,D,F,H]

I've tried strip function as

t1=[i.strip("vs")[0] for i in matches]
t2=[i.strip("vs")[-1] for i in matches]

But I'm not getting the desirable results. Can someone guide me trough it. Thanks

CodePudding user response:

I would use :

t1, t2 = map(list, zip(*[m.split(" vs ") for m in matches]))

And since you have a tag, here is any approach with split and the Series constructor :

t1, t2 = (
            pd.Series(matches)
                .str.split(" vs ", expand=True)
                .values
                .T.tolist()
          )

Output :

print(t1)
#['A', 'C', 'E', 'G']
print(t2)
#['B', 'D', 'F', 'H']

CodePudding user response:

Iterate over the matches list. Split each element on whitespace. Populate your lists.

matches=['A vs B','C vs D','E vs F','G vs H']

t1 = []
t2 = []

for match in matches:
    a, _, b = match.split()
    t1.append(a)
    t2.append(b)

print(t1)
print(t2)

Output:

['A', 'C', 'E', 'G']
['B', 'D', 'F', 'H']
  • Related