Splitting List That Contains Strings and Integers

myList = [ 4,'a', 'b', 'c', 1 'd', 3]

how to split this list into two list that one contains strings and other contains integers in elegant/pythonic way?

output:

myStrList = [ 'a', 'b', 'c', 'd' ]

myIntList = [ 4, 1, 3 ]

NOTE: didn’t implemented such a list, just thought about how to find an elegant answer (is there any?) to such a problem.

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

As others have mentioned in the comments, you should really start thinking about how you can get rid of the list which holds in-homogeneous data in the first place. However, if that really can’t be done, I’d use a defaultdict:

from collections import defaultdict
d = defaultdict(list)
for x in myList:
   d[type(x)].append(x)

print d[int]
print d[str]

Solution 2

You can use list comprehension: –

>>> myList = [ 4,'a', 'b', 'c', 1, 'd', 3]
>>> myIntList = [x for x in myList if isinstance(x, int)]
>>> myIntList
[4, 1, 3]
>>> myStrList = [x for x in myList if isinstance(x, str)]
>>> myStrList
['a', 'b', 'c', 'd']

Solution 3

def filter_by_type(list_to_test, type_of):
    return [n for n in list_to_test if isinstance(n, type_of)]

myList = [ 4,'a', 'b', 'c', 1, 'd', 3]
nums = filter_by_type(myList,int)
strs = filter_by_type(myList,str)
print nums, strs

>>>[4, 1, 3] ['a', 'b', 'c', 'd']

Solution 4

Split the list according to types found in the orginal list

myList = [ 4,'a', 'b', 'c', 1, 'd', 3]
types = set([type(item) for item in myList])
ret = {}
for typeT in set(types):
    ret[typeT] = [item for item in myList if type(item) == typeT]

>>> ret
{<type 'str'>: ['a', 'b', 'c', 'd'], <type 'int'>: [4, 1, 3]}

Solution 5

I’m going to summarize this thread by answering a Python FAQ “how do you write a method that takes arguments in any order, of a narrow range of types?”

Assuming the left-to-right order of all the arguments are not important, try this (based on @mgilson ‘s answer):

def partition_by_type(args, *types):
    d = defaultdict(list)

    for x in args:
        d[type(x)].append(x)

    return [ d[t] for t in types ]

def cook(*args):
    commands, ranges = partition_by_type(args, str, range)

    for range in ranges:
        for command in commands:
            blah blah blah...

Now you can call cook('string', 'string', range(..), range(..), range(..)). The argument order is stable, within its type.

# TODO  make the strings collect the ranges, preserving order

Solution 6

you can use this code as an example to create two different lists by using the function isdigit(),which checks for integers in a string.

ip=['a',1,2,3]
m=[]
n=[]
for x in range(0,len(ip):
    if str(ip[x]).isdigit():
        m.append(ip[x])
    else:n.append(ip[x])
print(m,n)

Solution 7

n = (input("Enter  string and digits: "))
d=[]
s=[]
for  x in range(0,len(n)):
    if str(n[x]).isdigit():
        d.append(n[x])
    else
        s.append(n[x])
print(d)
print(s)

Edit 1: Here is another solution

import re
x = input("Enter any string that contains characters and integers: ")
s = re.findall('[0-9]',x)
print(s)
c = re.findall('[a-z/A-Z]',x)
print(c)

Solution 8

myList = [ 4,'a', 'b', 'c', 1 'd', 3]

myList_string = []
myList_number = []

for a in myList:
  if type(a) == int or type(a) == float:
    myList_number.append(a)
  elif type(a) == str:
    myList_string.append(a)

Solution 9

import strings;
num=strings.digits;
str=strings.letters;
num_list=list()
str_list=list()
for i in myList:
    if i in num:
        num_list.append(int(i))
    else:
        str_list.append(i)

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply