简体   繁体   中英

Python - how to split a string list into two?

There is a list like:

list = ['AB', 'CD', 'EF', 'GH']

I would like to split this list like:

first =  ['A', 'C', 'E', 'G']
second = ['B', 'D', 'F', 'H']

Now I did like this :

for element in list:
    first.append(element[0])
    second.append(element[1])

Is it a good way? Actually, the length of list over 600,000.

You can try this:

list = ['AB', 'CD', 'EF', 'GH']

first, second = zip(*list)
print(first)
print(second)

Output:

('A', 'C', 'E', 'G')
('B', 'D', 'F', 'H')

Looping through the list and appending to a pair of empty list can be done something like the below shown example.

 list = ['AB', 'CD', 'EF', 'GH']
 first=[]
 second=[]
 for f in list:
    first.append(f[0])
    second.append(f[1])
 print(first)
 print(second)

The output would be like

['A', 'C', 'E', 'G']

['B', 'D', 'F', 'H']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM