【问题标题】:How do I loop through a large nested list in python?如何循环遍历python中的大型嵌套列表?
【发布时间】:2020-04-26 14:27:53
【问题描述】:

我了解如何遍历单个列表和单个数组。但是,我有一个嵌套列表,并且想在 same 索引中的每个嵌套列表中的第一个元素附加lon,然后再移动到下一个索引并重复该过程,直到所有索引都已完成附加。

0      [[[-105.077274, 40.514625], [-105.077005, 40.5...
1      [[[-105.024284, 40.509791], [-105.024274, 40.5...
2      [[[-105.087928, 40.578187], [-105.087939, 40.5...
3      [[[-105.11976, 40.589318], [-105.11977, 40.587...
4      [[[-105.083718, 40.568761], [-105.08459, 40.56...
                             ...
995    [[[-105.05362, 40.525161], [-105.053607, 40.52...
996    [[[-105.030003, 40.62114], [-105.030012, 40.62...
997    [[[-105.123316, 40.560645], [-105.123353, 40.5...
998    [[[-105.070162, 40.580083], [-105.070175, 40.5...
999    [[[-105.120617, 40.560044], [-105.120637, 40.5...
Name: geometry_coordinates, Length: 1000, dtype: object

目前,我的代码通过index 0 在第一个列表/元素-105.077274 中附加lon,但不是留在index 0,而是循环到index 1 并在下一个附加-105.024284

所以目前 lon 看起来像lon=[-105.077274,-105.024284...],但我试图让它先附加0 index,就像lon=[-105.077274,-105.077005...],然后再移动到index 1

import json
import pandas as pd 
from pandas.io.json import json_normalize

geojson = json.load(open("Data/Lanes.geojson"))

geojson = json_normalize(geojson['features'], sep="_")

print(geojson['geometry_coordinates'])

lon = []
lat = []

for longitude in geojson['geometry_coordinates']:
    lon.append(longitude[0][0][0])

任何帮助将不胜感激。

【问题讨论】:

  • 如果您有嵌套列表,请使用嵌套循环。
  • 这不是嵌套列表,它是熊猫数据框。
  • 我知道这看起来很眼熟。你为什么放弃你之前的,极其相似的问题?我想我们还需要更多信息,我不太明白问题出在哪里。
  • 这是解决我之前的问题的另一种方法,但不幸的是,它没有按预期工作。但是,我学到了一些新东西,所以一切都很好。

标签: python list loops append


【解决方案1】:

使用嵌套循环。

for l1 in geojson['geometry_coordinates']:
    for l2 in l1:
        for l3 in l2:
            lon.append(l3[0])
            lat.append(l3[1])

【讨论】:

  • 太棒了,谢谢!但是 3 个嵌套循环是如何覆盖 1000 个索引的呢?我不需要 1000 个嵌套循环吗?
  • 外循环处理所有行。
猜你喜欢
  • 1970-01-01
  • 2023-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-22
  • 1970-01-01
  • 2012-11-11
相关资源
最近更新 更多