python:将标量视为一个元素列表

时间:2013-09-15 15:55:47

标签: python list

我正在编写一个python脚本来处理从文件中读取的列表:

l = readListFromFile( myFile )
for i in l :
    # do something to each element

l有多个元素时,一切正常 但是,如果列表中只有一个元素readFromFile,则返回l作为标量,而不是列表。因此for i in l失败并出现错误

  

对象不可迭代

我无法控制readFromFile ,我的问题是即使ll,我怎样才能将{{1}}作为列表进行处理只有一个元素?

5 个答案:

答案 0 :(得分:3)

一个简单的解决方案是

l = readListFromFile(myFile)
try:
    i = iter(l)
    if isinstance(l, str):
        i = l 
except TypeError:
    i = [l]
for .... in i

即使您更改了readListFromFile以返回另一个可迭代的内容,这也会有效。

单线解决方案如果保证是str或列表(或其他可迭代的),只需

l = readListFromFile(myFile)
for e in [l] if isinstance(l, str) else l:

只使用三元运算符。

另外,有一个名为readList的方法......并不总是返回一个列表,这只是邪恶的。

答案 1 :(得分:2)

l = readListFromFile(myFile)
if isinstance(l, list):
    for i in l :
        # do something to each element
else:
    #do that something mentioned above

l = readListFromFile(myFile)
if isinstance(l, str):
    l = [l]
for i in l:
    #do that same something as above

l = readListFromFile(myFile)
try:
    for i in l:
        #do that something
except:
    #do that something with the value

如果你想要一个功能:

def get_me_a_list(var):
    if isinstance(var, list):
        return var
    return [var]

l = get_me_a_list(readListFromFile(myFile))
for i in l:
    #do your something

答案 2 :(得分:1)

使用生成器函数和isinstance

def solve(lis):
   if isinstance(lis, list):
      for item in lis:  #use just `yield from lis` in py3.x
         yield item
   else:
      yield lis

<强>演示:

>>> for item in solve(1):
...     print item
...     
1
>>> for item in solve([1, 2, 3]):
    print item
...     
1
2
3

要处理任何类型的可迭代,您可以使用collections.Iterable

from collections import Iterable
def solve(lis):
   if isinstance(lis, Iterable) and not isinstance(lis, basestring):
      for item in lis:  #use just `yield from lis` in py3.x
         yield item
   else:
      yield lis

答案 3 :(得分:1)

您可以将支票直接放入for-loop:

l = readListFromFile( myFile )
for i in (l if isinstance(l, list) else [l]):
    # Do something with i

答案 4 :(得分:0)

如果readFromFile返回标量而不是list,那么您可以自己将其转换为list

l = readListFromFile( myFile )
if not isinstance(l, list):
    l = [l]
for i in l :
    # do something to each element