繁体   English   中英

如何从 python 中列表的特定索引开始循环?

[英]How to start a loop from a specific index of a list in python?

我有这个 csv 文件,其中包含以下数据:

1 this_is_x, this_is_y
2 info about x, info about y
2 10,20
3 10,10
4 5,10

with open('my_file.csv') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
next(csv_reader)
for row in csv_reader:
    x, y = row
    list_x.append(x)
    list_y.append(y)

如何在没有前两行的情况下从 10,20 开始在 list_x 和 list_y 中附加 x 和 y 的循环?

如果重复next()语句,将在文件开头再跳过一行:

    import csv

    list_x = []
    list_y = []

    with open('my_file.csv') as csv_file:
        csv_reader = csv.reader(csv_file, delimiter=',')
        next(csv_reader)  # skip header line
        next(csv_reader)  # skip second line
        for x, y in csv_reader:
            list_x.append(x)
            list_y.append(y)

请注意在读取元组时如何避免使用中间变量。

据我所知, csv.reader()方法返回一个读取器object ,它遍历给定 CSV 文件中的行,这不是下标的。 您可以通过从csv.reader()返回的 object 创建一个列表来避免前两行,然后像 [2:] 一样将其切片以放弃 csv 文件的前两行。

代码如下:

import csv

list_x = []
list_y = []

with open('so_test.csv') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    for x, y in list(csv_reader)[2:]:
        list_x.append(x)
        list_y.append(y)

print(list_x)
print(list_y)

output 是:

['10', '10', '5']
['20', '10', '10']

[PS]:此代码在python 3.6.8 版本中测试。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM