VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > Python基础教程 >
  • Python代码阅读(第42篇):将输入转换成列表形式

本篇阅读的代码实现了将非列表形式的输入转换成列表形式。

本篇阅读的代码片段来自于30-seconds-of-python。

cast_list

def cast_list(val):
  return list(val) if isinstance(val, (tuple, list, set, dict)) else [val]

# EXAMPLES
cast_list('foo') # ['foo']
cast_list([1]) # [1]
cast_list(('foo', 'bar')) # ['foo', 'bar']

cast_list函数输入一个参数,输出该参数转换成列表的形式。

函数使用isinstance()检查给定的值是否是可枚举的,并通过使用list()将参数的形式进行转换,或直接封装在一个列表中返回。

原始代码片中没有setdict类型的样例,接下来我们测试一下这两种输入的输出。

>>> cast_list({'one', 'two', 'three'})
['three', 'one', 'two']
>>> cast_list({"one": 1, "two": 2, "three": 3})
['one', 'two', 'three']

集合类型的输出元素的顺序不一致,这是因为集合是无序。字典类型中,最后list中只有key,没有value

 

出处:https://www.cnblogs.com/felixz/p/15625119.html


相关教程