Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/blackberry/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 列表展平_Python_List - Fatal编程技术网

Python 列表展平

Python 列表展平,python,list,Python,List,我想将列表展平,但出现错误: def flatten_lists(nested): ''' >>> flatten_lists([[0], [1, 2], 3]) [0, 1, 2, 3] ''' list_of_lists = ([[0], [1, 2], 3]) List_flat = [] for i in range(len(list_of_lists)): for j in range (len(

我想将列表展平,但出现错误:

def flatten_lists(nested):
    '''
    >>> flatten_lists([[0], [1, 2], 3])
    [0, 1, 2, 3]
    '''
    list_of_lists = ([[0], [1, 2], 3])
    List_flat =  []
    for i in range(len(list_of_lists)): 
      for j in range (len(list_of_lists[i])): 
        List_flat.append(list_of_lists[i][j]) 
    return List_flat

如何解决这个问题您试图将外部列表的每个元素都当作一个列表来对待。问题是内部列表中的某些元素不是列表。特别是代码的一个简单修复方法是将内部
for
循环包装在
try
/
中,除了
块:

TypeError: object of type 'int' has no len()

最后一个元素
3
,没有包装在列表构造函数中,因此当
i
是最后一个元素时,您试图将长度取为单个整数,这是没有意义的。似乎您需要拿出一些逻辑来测试
len
是否存在python中最好的方法就是我在这里所做的-尝试遍历它,如果它失败,那么它就不是子列表。从技术上讲,您还可以检查元素是否具有迭代所需的构造(即
\uuuu iter\uuuu()
方法),但这既容易混淆,也可能会因自定义数据类型而失败。
for i in range(len(list_of_lists)): 
    try:  # if the element is a list then add it
        for j in range (len(list_of_lists[i])): 
            List_flat.append(list_of_lists[i][j]) 
    except TypeError:  # so, if iteration fails, the element isn't a list
        List_Flat.append(list_of_lists[i])