Python:如何根据给定列表中的数值和字符串分隔列表

Bha*_*yap 0 python

考虑我有一个像这样的列表

listed = [1, 't', 'ret', 89, 95, 'man65', 67, 'rr']
Run Code Online (Sandbox Code Playgroud)

现在我需要编写一个类似于2个列表的脚本; 一个stringListnumberList地方,

stringList = ['t', 'ret', 'man65', 'rr']
numberList = [1, 89, 95, 67]
Run Code Online (Sandbox Code Playgroud)

use*_*450 6

检查您所拥有的对象类型的标准方法是使用isinstance(object,classinfo)函数.使用isinstance(...)优先于类型(对象),因为type(...)返回对象的确切类型,并且在检查类型时不考虑子类(这在更复杂的场景中很重要).

您可以检查,如果你有一个数字(int,float每一类单独或与比较等)numbers.Number:

# Check for any type of number in Python 2 or 3.
import numbers
isinstance(value, numbers.Number)

# Check for floating-point number in Python 2 or 3.
isinstance(value, float)

# Check for integers in Python 3.
isinstance(value, int)

# Check for integers in Python 2.
isinstance(value, (int, long))
Run Code Online (Sandbox Code Playgroud)

你可以通过比较各个类来检查你是否有一个字符串(str,bytes等),这取决于你使用的是Python 2还是3:

# Check for unicode string in Python 3.
isinstance(value, str)

# Check for binary string in Python 3.
isinstance(value, bytes)

# Check for any type of string in Python 3.
isinstance(value, (str, bytes))

# Check for unicode string in Python 2.
isinstance(value, unicode)

# Check for binary string in Python 2.
isinstance(value, str)

# Check for any type of string in Python 2.
isinstance(value, basestring)
Run Code Online (Sandbox Code Playgroud)

所以,把所有这些放在一起你就会:

import numbers

stringList = []
numberList = []
for value in mixedList:
    if isinstance(value, str):
        stringList.append(value)
    elif isinstance(value, numbers.Number):
        numberList.append(value)
Run Code Online (Sandbox Code Playgroud)