简体   繁体   中英

Splitting a list of strings with a delimiter and adding to new lists

This is my list:

names = ['blue v orange', 'white v black', 'red v brown']  

I want to split them by ' v ' and append to a new list like this:

['blue', 'white', 'red']  # first
['orange', 'black', 'brown']  # second

How can I append them after splitting? The below code does not work:

first = []
second = []

for x in names:
    first, second = x.split(' v ')

You can use zip :

names = ['blue v orange', 'white v black', 'red v brown']  
first, second = map(list, zip(*map(lambda x:x.split(' v '), names)))  
print(first)
print(second)

Output:

['blue', 'white', 'red'] 
['orange', 'black', 'brown']

Here is a pythonic solution:

names = ['blue v orange', 'white v black', 'red v brown']

x, y = list(zip(*(k.split(' v ') for k in names)))

x  # ('blue', 'white', 'red')
y  # ('orange', 'black', 'brown')

Just append to each list separately, but be careful not to reuse your variable names:

names = ['blue v orange', 'white v black', 'red v brown']  
first = []
second = []
for x in names:
    f, s = x.split(' v ')
    first.append(f)
    second.append(s)

print(first, second)

Results in:

['blue', 'white', 'red'] ['orange', 'black', 'brown']

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