Python:将标量视为一个元素列表 [英] python: treating a scalar as a one element list

查看:67
本文介绍了Python:将标量视为一个元素列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am writing a python script that process lists read from a file:

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

l具有多个元素时,一切正常.
但是,当列表中只有一个元素时,readFromFile返回l作为标量而不是列表.因此for i in l失败并显示错误

All works fine when l has more than one element.
However, when there is only one element in the list readFromFile returns l as a scalar and not as a list. Hence for i in l fails with error

对象不可迭代

object is not iterable

我无法控制readFromFile ,我的问题是,即使l仅具有单个元素,我如何使python将l视为列表? /p>

I have no control over readFromFile, and my question is how can I make python treat l as a alist even in the case where l has only a single element?

推荐答案

一个简单的解决方案是

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

即使您更改了readListFromFile以返回另一个可迭代对象,这也将起作用.

This will work even if you change what readListFromFile to return another iterable.

如果可以保证是一个str或一个列表(或其他可迭代的),那么一个衬板解决方案就是

A one liner solution if it's guaranteed to be a str or a list (or other iterable) is just

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

仅使用三元运算符.

顺便说一句,拥有一个名为readList的方法...并不总是返回列表就是邪恶的.

On an aside, having a method called readList... not always returning a list is just evil.

这篇关于Python:将标量视为一个元素列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆