如何在Python中修改列表?

3
你能帮我修改我的列表吗?我有一个由三个坐标X Y Z组成的列表。我需要生成一个字符串,其中X Y坐标由逗号分隔,每个坐标由换行符分隔。
xyz = ['55.548745 35.547852 5.545', '57.85425 37.524852 7.545', '57.214445 38.587852 6.745']

结果应该如下所示:
xy = "55.548745,35.547852
     57.854258,37.524852
     57.214445,38.587852"

如何实现这一功能?非常感谢您的帮助。


对我来说结果似乎有点含混不清,你想要输出是一个包含每个字符串中用逗号分隔的坐标的字符串列表,还是想要结果是一个包含浮点数元组的列表? - Chi
@DaichiJameson 我希望输出为字符串列表。每组新的x y坐标都应该在新行中。谢谢。 - linasster
4个回答

1
将每个子列表中的前两个项目添加到新的 xy 列表中:
xyz = ['55.548745 35.547852 5.545', '57.85425 37.524852 7.545', '57.214445 38.587852 6.745']

x = []
y = []

for p in xyz:
    x1, y1 = p.split()[:-1]
    x.append(float(x1))
    y.append(float(y1))

print(x)
print(y)

输出:

[55.548745, 57.85425, 57.214445]
[35.547852, 37.524852, 38.587852]

现在您有两个与原始列表相同顺序的列表,因此可以引用相应的 (x,y) 点:
print(x[0], y[0])

返回一个元组,其中包含第一个坐标:
(55.548745, 35.547852)

1
这是我的解决方案,使用 split()[:-1] 来移除 z,然后返回一个由 xy 组成的 tuple 列表。
xyz = ['55.548745 35.547852 5.545', '57.85425 37.524852 7.545', '57.214445 38.587852 6.745']
new_list = [(float(x2), float(y2)) for (x2, y2) in [x1.split()[:-1] for x1 in xyz]]
print(new_list)

输出:

[(55.548745, 35.547852), (57.85425, 37.524852), (57.214445, 38.587852)]

1

这里是另一个答案,它使用字典推导式从您的输入列表中提取纬度和经度。接下来,代码遍历这两个字典并获取纬度和经度值。

xyz = ['55.548745 35.547852 5.545', '57.85425 37.524852 7.545', '57.214445 38.587852 6.745']

geo_latitude = {y:x.split()[0] for y,x in enumerate(xyz)}
geo_longitude = {y:x.split()[1] for y,x in enumerate(xyz)}

for (latitude_key,latitude_value),(longitude_key,longitude_value) in zip(geo_latitude.items(), geo_longitude.items()):

# I'm using f-strings to format and print the strings
print(f'Lat/Long Coordinates -- {latitude_value}, {longitude_value}')
# outputs
Lat/Long Coordinates -- 55.548745, 35.547852
Lat/Long Coordinates -- 57.85425, 37.524852
Lat/Long Coordinates -- 57.214445, 38.587852

1

您可以使用:

xy = '\n'.join([','.join(coord.split(' ')[0:2]) for coord in xyz])

这将迭代每个xyz坐标,按空格拆分它们,将前两个坐标用逗号连接并生成一个列表。然后通过换行符将列表连接起来,创建所需的结果。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接