列表展平

时间:2019-11-11 23:06:50

标签: 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(list_of_lists[i])): 
        List_flat.append(list_of_lists[i][j]) 
    return List_flat

我想整理列表[[0], [1, 2], 3],但出现错误:

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

如何解决这个问题

1 个答案:

答案 0 :(得分:0)

您正在尝试将外部列表的每个元素都视为一个列表。问题在于内部列表中的某些元素不是列表。一个简单的代码修复方法是将内部input .apply("Convert to TableRow", ParDo.of(new DoFn<KV<Integer, String>, TableRow>() { @ProcessElement public void processElement(ProcessContext c) { JSONObject message = new JSONObject(c.element().getValue()); TableRow row = new TableRow(); message.keySet().forEach(key -> { Object value = message.get(key); row.set(key, value); }); c.output(row); }})) .apply( BigQueryIO.writeTableRows() .to("PROJECT_ID:DATASET_NAME.dynamic_bq_schema") .withSchemaFromView(schemaView) .withCreateDisposition(BigQueryIO.Write.CreateDisposition.CREATE_IF_NEEDED) .withWriteDisposition(BigQueryIO.Write.WriteDisposition.WRITE_APPEND)); 循环包装在for / try块中:

except