我有一个字典
{country: [coordinate_set1,
coordinate_set2,
coordinate_set3]}
其中每个coordinate_set当前是一串长的坐标对。
如何访问每个coordinate_set
并将其拆分为每对x_coord;y_coord
的列表
{country: [[set1_pair1][set1_pair2][set1_pair...],
[set2_pair1][set2_pair2][set2_pair...],
[set3_pair1][set3_pair2][set3_pair...]}
然后最后,在这些列表中,创建每对x_coord, y_coord
{country: [[x1_1,y1_1][x1_2,y1_2][x1_...,y1_],
[x2_1,y2_1][x2_2,y2_2][x2_...,y2_],
[x3_1,y3_1][x3_2,y3_2][x3_...,y3_]}
由于这些值是以空格分隔和以分号分隔的,因此在每个字符串元素上使用.split(" ")
和.split(";")
应该相当简单,但我无法弄清楚如何索引和保存拆分
我觉得它应该像
那样for country, coordinate in dict.items():
for coordinate_set in coordinate:
split_set = coordinate_set.split(sep = " ")
for xy_set in split_set:
xy_tuple = tuple(xy_set.split(sep = ";")
但我无法真正了解如何保存这些内容。
示例数据: 编辑:已更新样本数据
Antarctica
-80.0401787251;-59.5720946926 -80.5496566711;-59.865849372
-79.4970594217;-159.20818356 -79.634208673;-161.127601285
-78.0470696006;-45.1547576564 -78.4781027223;-43.9208278062
答案 0 :(得分:3)
这应该这样做,列表和字典理解的组合:
{country: [tuple(xy_set.split(';')) for cordinate_set in coordinate for xy_set in in cordinate_set.split()] for country, coordinate in dict.items()}
101
方式:
result = {}
for for country, coordinate in dict.items():
for cordinate_set in coordinate:
for xy_set in in cordinate_set.split():
e = tuple(xy_set.split(';'))
if country in result:
result[country].append(e)
else:
result[country] = [e]
答案 1 :(得分:2)
Python 101方式
dict1={'Antarctica':
['''-80.0401787251;-59.5720946926 -80.5496566711;-59.865849372
-79.4970594217;-159.20818356 -79.634208673;-161.127601285
-78.0470696006;-45.1547576564 -78.4781027223;-43.9208278062''']}
for country, coordinate in dict1.items():
cs=[]
for coordinate_set in coordinate:
split_set = coordinate_set.split(sep = " ")
ss=[]
for xy_set in split_set:
xy_tuple = tuple(xy_set.split(sep = ";"))
ss+=[xy_tuple]
cs+=ss
dict1[country]=cs
print(dict1)
答案 2 :(得分:0)
不使用理解和较少的代码行进行微小修改
data={'Antarctica':
["""-80.0401787251;-59.5720946926 -80.5496566711;-59.865849372
-79.4970594217;-159.20818356 -79.634208673;-161.127601285
-78.0470696006;-45.1547576564 -78.4781027223;-43.9208278062"""],'Ameriica':
["""-80.0401787251;-59.5720946926 -80.5496566711;-59.865849372
-79.4970594217;-159.20818356 -79.634208673;-161.127601285
-78.0470696006;-45.1547576564 -78.4781027223;-43.9208278062"""]}
for key,value in data.items():
#print value
updatevalue=[]
inlist=value[0].split()
for i in inlist:
updatevalue.append(tuple(i.split(';')))
data.update({key:updatevalue})
print data