传递一个不可迭代的list.extend() [英] Passing a non-iterable to list.extend ()

查看:100
本文介绍了传递一个不可迭代的list.extend()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个公共方法,以允许调用方将值写入设备,例如,将其称为write_vals().

I am creating a public method to allow callers to write values to a device, call it write_vals() for example.

由于这些值是实时输入的,因此我想通过允许它们键入列表或单个值(取决于需要写入多少个值)来简化用户的工作.例如:

Since these values will be typed live, I would like to simplify the user's life by allowing them type in either a list or a single value, depending on how many values they need to write. For example:

write_to_device([1,2,3])

write_to_device(1)

我的函数想使用一个平面列表,因此我尝试变得更聪明并编写如下代码:

My function would like to work with a flat list, so I tried to be clever and code something like this:

input_list = []  
input_list.extend( input_val )

当用户输入列表时,它会顺畅地工作,但是当用户输入一个整数时,它会失败:

This works swimmingly when the user inputs a list, but fails miserably when the user inputs a single integer:

TypeError:"int"对象不可迭代

TypeError: 'int' object is not iterable

使用list.append()会在传入列表时创建一个嵌套列表,这将使扁平化变得更加麻烦.

Using list.append() would create a nested list when a list was passed in, which would be an additional hassle to flatten.

检查传入的对象的类型似乎笨拙且不具有Python风格,并希望list.extend()可以接受不可迭代对象使我无处可去.因此,尝试了多种其他编码方法.

Checking the type of the object passed in seems clumsy and non-pythonic and wishing that list.extend() would accept non-iterables has gotten me nowhere. So has trying a variety of other coding methods.

建议(请仅与编码相关).

Suggestions (coding-related only, please) would be greatly appreciated.

推荐答案

您可以使用try...except...:

try:
    input_list = list(input_val)
except TypeError:
    input_list = list((input_val,))

这是pythonic.

This is pythonic.

PS:可变参数,如 @sth提出的会更好,但是为了完整起见,我保留了这个答案.有时您不能使用可变参数.

P.S.: Variable parameters, as @sth proposes, is much better, but I leave this answer for completeness. Sometimes you cannot use variable parameters.

这篇关于传递一个不可迭代的list.extend()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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