How do I split a list in an alphabetical range? I need to filter out a list with ranges "a" through "m" and ranges "n" through "z"

Viewed 211

I have a main list which contains key value pairs that I would like to split into two separate lists. First half ranges A-M and second half ranges N-Z.

example of data trying to split:

Main_list = ['a 1', 'her 1', 'her 1', 'lately','mr 1', 'ornament 1', 
             'pleased 1', 'saturday 1', 'view 1', 'youth 1']

Result of data split:

list1 = ['a 1', 'her 1', 'her 1', 'lately','mr 1']

list2 = ['ornament 1', 'pleased 1', 'saturday 1', 'view 1', 'youth 1']
3 Answers

You can do something like this.

Main_list = ['a 1', 'her 1', 'her 1', 'lately','mr 1', 'ornament 1', 
             'november 3', 'pleased 1', 'saturday 1', 'view 1', 'youth 1']
list1,list2 = [],[]
for i in Main_list:
    if i[0].lower() <'n':
        list1.append(i)
    else:
        list2.append(i)

print (list1)
print (list2)

Your output will be:

['a 1', 'her 1', 'her 1', 'lately', 'mr 1']
['ornament 1', 'november 3', 'pleased 1', 'saturday 1', 'view 1', 'youth 1']

I want to caution you about this solution. If the first char in the string is not an alphabet (is a numeric or non alphabet character), then the list will have wrong values. Let me know if you want me to address that as well

You can use ord() and chr() to generate list from a to m and use them in list comprehension as:

Main_list = ['a 1', 'her 1', 'her 1', 'lately','mr 1', 'ornament 1', 
             'pleased 1', 'saturday 1', 'view 1', 'youth 1']

a_to_m_chars = [chr(i) for i in range(ord('a'), ord('n'))]
list1 = [elt for elt in Main_list if elt[0].lower() in a_to_m_chars]
list2 = [elt for elt in Main_list if elt[0].lower() not in a_to_m_chars]
print(list1)
print(list2)

Update: You don't need to create a new list but can do conditionally in list comprehension itself as:

list1 = [elt for elt in Main_list if elt[0].lower() >= 'a' and elt[0].lower() <= 'm']
list2 = [elt for elt in Main_list if elt[0].lower() >= 'n' and elt[0].lower() <= 'z']

Filtering the list based on first character's ord

>>> list(filter(lambda entry :  ord('a') <= ord(entry.lower()[0]) <= ord('m'), l))
['a 1', 'her 1', 'her 1', 'lately 1', 'mr 1']

>>> list(filter(lambda entry :  ord('n') <= ord(entry.lower()[0]) <= ord('z'), l))
['ornament 1', 'pleased 1', 'saturday 1', 'view 1', 'youth 1']
Related