我有一个变量,可以是单个字符串或字符串列表。当变量是单个字符串时,循环通过char迭代它。
text = function() # the function method can return a single string or list of string
for word in text:
print word+"/n"
# When it is a single string , it prints char by char.
我希望循环在单个字符串时只迭代一次。我实际上不想使用其他循环类型。我怎样才能为每个结构做到这一点?
答案 0 :(得分:5)
如果你的函数总是返回一个列表,即使只有一个元素,也会更清晰。如果你可以在那里更改你的代码,我强烈推荐这个。
否则在循环之前添加此行:
sh
此外,您的变量名称令人困惑,您应该调用“text”“word_list”或其他东西,以便更好地指出所需的类型。
要求类型检查通常表示样式问题。
答案 1 :(得分:1)
这应该这样做:
text = function()
if isinstance(text, list):
for word in text:
print word + "/n"
else:
print text + "/n"
答案 2 :(得分:0)
尽管鸭子打字是常态,但有时你只需要检查某种东西的类型。在这种情况下,您需要一些实例basestring
。
text = function()
if isinstance(text, basestring):
print text
else:
for word in text:
print word
答案 3 :(得分:0)
您需要isinstance()
方法来检查变量所持有的值的类型,根据文档:
如果object参数是classinfo参数的实例,或者是(直接,间接或虚拟)子类的实例,则返回true。
使用它可以创建自定义函数:
import collections
def my_print(my_val):
if isinstance(my_val, str):
print my_val
elif isinstance(my_val, collections.Iterable): # OR, use `list` if you just want check for list object
# To check object is iterable ^
for val in my_val:
print val
else:
raise TypeError('Unknown value')
示例运行:
>>> my_print('Hello')
Hello
>>> my_print(['Hello', 'World'])
Hello
World
instance()
检查传递的对象是否是传递的类的实例。
>>> isinstance('hello', str)
True
>>> isinstance('hello', list)
False
或者,您可以使用type()
检查变量类型:
>>> type('hello') == str
True
答案 4 :(得分:0)
仍然可以使用duck typing,你只需要在列表中使用不在字符串中的方法,反之亦然,并捕获异常,例如copy()
是列表但不是str的方法。
text = function()
try:
temp_text = text.copy()
for word in text:
print word
except AttributeError:
print text
在上面的代码中,如果function()
返回一个字符串text.copy()
将引发一个AttributeError异常,并且不会通过for循环,而是转到异常块并按原样打印文本,另一个如果text.copy()
成功,则表示它是一个列表,并继续执行for循环以打印列表中的每个单词。
答案 5 :(得分:0)
我选择了这一点,因为它着重于为循环做准备,而不是基本的循环(重新)设计:
if type(thing) is str:
x = [thing]
elif type(thing) is list:
x = thing[:]
for i in x:
... do stuff ....