如何将列表中的整数和字符串元素分成两个不同的列表?

时间:2017-03-18 18:41:44

标签: python python-2.7

我想将列表中的整数和字符串元素分成两个不同的列表。 即

list1=[1,"Red",2,"Blue",3,"Pink",4,"White",5,"Yellow"] 

分成

intList=[1,2,3,4,5]
strList=["Red","Blue","Pink","White","Yellow"]

我写这段代码

import string
digits=string.digits
strings=string.letters + '_' + digits
list1=[1,"Red",2,"Blue",3,"Pink",4,"White",5,"Yellow"]
number=[]
string=[]
for item in list1:
    if item in digits:
        number.append(item)
    if item in strings:
        string.append(item)
print "List of String is:",string
print "List of Digits is:",number

但它会出错:" ' in'要求字符串作为左操作数,而不是int"

如何以另一种方式编写此程序?

1 个答案:

答案 0 :(得分:1)

你可以使用函数将它们分开,无论它们是否按任何顺序

def separate(array, type):
    return [n for n in array if isinstance(n, type)]

array = [ 1,"Red",2,"Blue",3,"Pink",4,"White",5,"Yellow"]
digits = separate(myList,int)
strings = array(myList,str)
print digits, strings

如需进一步帮助,请参阅  Python - Splitting List That Contains Strings and Integers