如何从Python元组或列表中提取字符串?

时间:2019-04-23 22:58:25

标签: python python-3.x list while-loop tuples

我不知道为什么它不起作用,但是我是编程新手,所以我可能会犯一些简单的错误。

def tuplasemstr(t):
    tup1 = []
    n = 0
    while n <= 2 and type(t[n],) != str:
        list.append(tup1, t[n])
        n = n + 1

    return tuple(tup1)

我期望像这样:

t = ("a",3,2.1)

输出:

(3,2.1)

2 个答案:

答案 0 :(得分:3)

@blhsing提供的解决方案是最好的。但是,如果要使代码正常工作,可以执行以下操作:

def tuplasemstr(t):
    tup1 = []
    n = 0
    while n < len(t):
        if not isinstance(t[n], str):
            list.append(tup1, t[n])
        n = n + 1
    return tuple(tup1)

t = ('a', 3, 2.1, 'c', 32)
print(tuplasemstr(t)) # (3, 2.1, 32)

要检查字符串,应在while循环内使用isinstance。另外,请勿使用n <= 2对长度进行硬编码,而应使用n < len(t)

答案 1 :(得分:2)

如果要过滤掉元组中的字符串项,则可以使用生成器表达式,条件是测试该项是否不是字符串的实例:

def tuplasemstr(t):
    return tuple(i for i in t if not isinstance(i, str))
相关问题