![](/img/trans.png)
[英]Python: how do I iterate only if value is a tuple/list and not a string
[英]How to iterate through Tuple<List<String>> in Python
class App:
def filter(*input):
result = []
print(type(input))
for arrayOfColors in input:
print(type(arrayOfColors))
goodColors = getGoodColors(arrayOfColors)
result.add(goodColors)
return result
def getGoodColors(arrayOfColors):
setOfNotGoodColors = ["gray", "yellow", "purple"]
goodColors = []
for color in arrayOfColors:
if color not in setOfNotGoodColors:
goodColors.add(color)
return goodColors
app = App()
app.filter(["blue", "red"], ["gray","blue"])
编译的结果是:
<class '__main__.App'>
Traceback (most recent call last):
File "<string>", line 20, in <module>
File "<string>", line 7, in filter
File "<string>", line 14, in getGoodColors
TypeError: 'App' object is not iterable
如何摆脱这个错误? 我必须写更多的不是代码字符,请帮助。
如果在def filter(*input):
下添加print(input)
就可以看到问题: 你会看到的
(<__main__.App object at 0x00000211E39C0A48>, ['blue', 'red'], ['gray', 'blue'])
这是每个 class 中self
的结果。 您可以在for
循环中使用[1:]
切片来避免它。 此外, python list
没有名为add
的属性; 它们被称为append
:
class App:
def filter(*input):
result = []
for arrayOfColors in input[1:]:
goodColors = getGoodColors(arrayOfColors)
result.append(goodColors)
return result
def getGoodColors(arrayOfColors):
setOfNotGoodColors = ["gray", "yellow", "purple"]
goodColors = []
for color in arrayOfColors:
if color not in setOfNotGoodColors:
goodColors.append(color)
return goodColors
app = App()
app.filter(["blue", "red"], ["gray","blue"])
请注意,将变量命名为内置函数采用的名称是一种不好的做法,因此最好将input
变量命名为my_input
。
在 python class 内部,每个方法都应该有一个self
参数,例如:
class App:
def filter(self, *input):
使用 self 参数,您可以访问该实例的属性。
另一个问题是:为了向 python 列表添加值,您需要使用 function append
,例如:
goodColors.append(color)
您的最终代码应如下所示:
class App:
def filter(self, *input):
result = []
print(type(input))
for arrayOfColors in input:
print(type(arrayOfColors))
goodColors = getGoodColors(arrayOfColors)
result.append(goodColors)
return result
def getGoodColors(arrayOfColors):
setOfNotGoodColors = ["gray", "yellow", "purple"]
goodColors = []
for color in arrayOfColors:
if color not in setOfNotGoodColors:
goodColors.append(color)
return goodColors
app = App()
app.filter(["blue", "red"], ["gray","blue"])
注意:您不应该使用名称输入作为参数,因为它是内置 function 的名称,但是即使您使用它,代码也会运行,所以我没有修复它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.