我不明白为什么它不起作用,但我是编程新手,所以我可能会犯一些简单的错误。
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)
请您参考如下方法:
@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)
要检查字符串,您应该使用 isinstance在 while 循环内。另外,不要使用 n <= 2 对长度进行硬编码, 使用 n < len(t)相反。
