1

I have a list like this

[
    'agronomy salenrollment services,3',
    'online account manager,1',
    'game day manager,15',
    'leader biologist,16'
]

How I can separate numbers and make 2 different list?

output:

l1 = [
    'agronomy salenrollment services',
    'online account manager',
    'game day manager',
    'leader biologist'
]

l2 = [3, 1, 15, 16]

3 Answers 3

3

You can using a generator expression with zip() to achieve this as:

my_list = [
    'agronomy salenrollment services,3',
    'online account manager,1',
    'game day manager,15',
    'leader biologist,16'
]

l1, l2 = zip(*(s.split(',') for s in my_list))

where l1 and l2 will hold:

>>> l1
('agronomy salenrollment services', 'online account manager', 'game day manager', 'leader biologist')

>>> l2
('3', '1', '15', '16')

Note: l1 and l2 are of type tuple in above example instead of list. If it is must for you to have these as list, then you can type-cast them to list using map() as:

l1, l2 = map(list, zip(*(s.split(',') for s in my_list)))
#             ^ To type-cast to `list`

In the above solutions, l2 is holding value as string of numbers. You can use map() again on l2 to type-cast all the elements in the list to int type. For example:

l2 = list(map(int, l2))
# where `l2` will now hold:
#     [3, 1, 15, 16]
Sign up to request clarification or add additional context in comments.

Comments

0

It's simple - loop through each item in the list and split it on the ",":

original_list = ['agronomy salenrollment services,3', 
 'online account manager,1',
 'game day manager,15',
 'leader biologist,16']

l1 = [] # all strings
l2 = [] # all numbers

for item in original_list:
    split = item.split(",") # split on commas in string
    l1.append(split[0]) # add string to l1
    l2.append(int(split[1])) # add string as integer to l2

Or, using list comprehension: (Note that this solution will loop through the list twice, so if you want to save time, use the single for loop).

l1 = [item.split(",")[0] for item in original_list]
l2 = [item.split(",")[1] for item in original_list]

Comments

0

map returns a map class. The splitString return a tuple with two string elements. The map class can be iterated and the list of tuples unpacked and appended to the two lists.

list1=[
    'agronomy salenrollment services,3',
    'online account manager,1',
    'game day manager,15',
    'leader biologist,16'
]

def splitString(paramString):
    a,b=paramString.split(",") 
    return a,b

result=map(splitString,list1)

list1=[]
list2=[]

[(list1.append(item[0]), list2.append(item[1])) for item in result]

print(list1,list2)

output:

['agronomy salenrollment services', 'online account manager', 'game day manager', 'leader biologist'] 
['3', '1', '15', '16']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.