如何将一个列表的项目逐一添加到另一个列表?

How to add one list's items to another list, one by one?

我有一个 csv 文件,其中包含如下所示的一些内容:

name,x,y
N1,30.2356,12.5263
N2,30.2452,12.5300

...继续进行。

这是我尝试过的,我从 .csv 中调用它们并分别添加到不同的列表中。

import csv

nn = []
xkoor = []
ykoor = []
coord = []
with open('C:/Users/Mert/Desktop/py/transformation/1.csv', 'r') as f:
    reader = csv.reader(f)
    for row in reader:
        nn.append(row[0].split(','))
        xkoor.append(row[1].split(','))
        ykoor.append(row[2].split(','))

j = 1
for i in range(len(xkoor)):
    for j in range(len(ykoor)):

我正在尝试将列表列为:

coord = [30.2356,12.5263],[30.2452,12.5300],....

我不知道该怎么做。有什么想法吗?

看来你把事情搞得太复杂了。

如果您要做的只是创建一个仅包含 X 和 Y 值的坐标数组,那么您可以通过以下方式实现:

import csv
coord = []
with open('C:/Users/Mert/Desktop/py/transformation/1.csv', 'r') as f:
    reader = csv.reader(f)
    for row in reader:
        rowlist = row.split(',')
        coord.append(rowlist[1:3])
print(coord)

您需要做的就是在每行的基础上提取一个子集,并将其附加到您的坐标数组中。无需每次都调用行拆分,或为轴创建单独的数组。

K.I.S.S!

(另外,忠告 - 不要将 PII 放在你的问题中。无需使用你的整个 windows 文件路径,只需指明它是一个 CSV 文件即可。我不需要知道你的回答问题的名字!)

您不应该自己用逗号分隔字符串,因为 csv.reader 已经为您做了。只需遍历 csv.reader 生成器并根据需要解压缩列:

reader = csv.reader(f)
next(reader)
coord = [[float(x), float(y)] for _, x, y in reader]

为什么不pandas?!

  • read_csv 将准备好您的文件并转换为数据帧
  • 迭代行并访问列 x 和 y
  • 合并成list

而且更容易使用

    import pandas as pd
    df = pd.read_csv('1.csv', header=0)
    [[r.x, r.y] for _, r in df.iterrows()]

结果:

[[30.2356, 12.5263], [30.2452, 12.53]]

csv-reader 应该默认用逗号为您拆分行:

import csv

with open('somefile.csv') as fh:
    reader = csv.reader(fh)
    for row in reader:
        print(row)

# outputs
['name', 'x', 'y']
['N1', '30.2356', '12.5263']
['N2', '30.2452', '12.5300 ']

考虑到这一点,如果您只是想遍历坐标,您可以使用解包来获取 xy,然后通过附加元组来构建列表:

import csv

coords = []

with open('somefile.csv') as fh:
    reader = csv.reader(fh)
    next(reader) # skips the headers
    for row in reader:
        name, x, y = row
        coords.append((float(x), float(y)))

# then you can iterate over that list like so
for x, y in coords:
    # do something

坐标将如下所示:

[(30.2356, 12.5263), (30.2452, 12.53)]

我会这样做:

import csv

# coordinates as strings 
with open('some.csv', 'r') as f:
    cord = [a for _, *a in csv.reader(f)]

# coordinates as floats
with open('some.csv', 'r') as f:
    cord = [[float(x), float(y)] for _, x, y in csv.reader(f)]

[print(xy) for xy in cord]

如果你喜欢单线:

data = """name,x,y
N1,30.2356,12.5263
N2,30.2452,12.5300"""

coords = [[x,y]
          for line in data.split("\n")[1:]
          for _,x,y in [line.split(",")]]
print(coords)

这会产生

[['30.2356', '12.5263'], ['30.2452', '12.5300']]