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

时间:2015-05-14 13:26:54

标签: python

考虑我有一个像

这样的清单
listed = [1, 't', 'ret', 89, 95, 'man65', 67, 'rr']

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

stringList = ['t', 'ret', 'man65', 'rr']
numberList = [1, 89, 95, 67]

5 个答案:

答案 0 :(得分:6)

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

您可以通过单独比较每个班级或使用numbers.Number来检查您是否有号码(intfloat等):

# 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))

您可以通过比较各个类来检查您是否有字符串(strbytes等),具体取决于您是否使用Python 2或3: / p>

# 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)

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

import numbers

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

答案 1 :(得分:2)

numbers, strings = both = [], []
for x in listed:
    both[isinstance(x, str)].append(x)

另一种选择是回答Ajay在评论中的挑战,只需要一个列表理解(注意:这是一个糟糕的解决方案):

strings = [listed.pop(i) for i, x in list(enumerate(listed))[::-1] if isinstance(x, str)][::-1]
numbers = listed

另:

numbers, strings = [[x for x in listed if isinstance(x, t)] for t in (int, str)]

另一个,只有一次阅读listed的优势(受PM 2Ring启发):

numbers, strings = [[x for x in l if isinstance(x, t)]
                    for l, t in zip(itertools.tee(listed), (int, str))]

答案 2 :(得分:1)

您可以使用内置的type函数来测试列表中的每个元素,并将其附加到基于其类型的列表中。

numberList = []
stringList = []

for x in listed:
    if type(x) == int: numberList.append(x)
    else: stringList.append(x)

答案 3 :(得分:1)

In [16]: sl=[i for i in a if isinstance(i,str)]

In [17]: nl=[i for i in a if isinstance(i,int)]

In [18]: sl
Out[18]: ['t', 'ret', 'man65', 'rr']

In [19]: nl
Out[19]: [1, 89, 95, 67]

答案 4 :(得分:1)

通用解决方案:按完全对象类型进行分组。

multityped_objects = [1, 't', 'ret', 89, 95, 'man65', 67, 'rr', 12.8]
grouped = {}
for o in multityped_objects:
    try:
        grouped[type(o)].append(o)
    except KeyError:
        grouped[type(o)] = [o]

assert grouped[str] == ['t', 'ret', 'man65', 'rr']
assert grouped[int] == [1, 89, 95, 67]
assert grouped[float] == [12.8]