Python 从 CSV 创建嵌套列表

标签 python python-3.x list csv read.csv

我需要将数据从 csv 文件导入到 python 中,形成如下所示的列表:

list1 = [[(0, 0), (0, 1), (0, 2)],
         [(1, 0), (1, 1), (1, 2)],
         [(2, 0), (3, 1), (3, 2)]]

这样我就可以访问元素

list1[0] = [(0, 1), (0, 2),(0, 3)]    # type list

list1[0][0] = (0,1)    # type tuple

list1[0][0][0] = 0    #type int

我在 csv 文件中有整数,我可以根据需要对其进行操作。没有特定的格式要求 现在数据是六列,没有间距,或者每行六个整数

我尝试了这段代码,但它没有按我想要的方式工作:

import csv

with open('file1.csv', 'r') as f:
  reader = csv.reader(f)
  list1 = list(reader)

print(list1)

最佳答案

您需要做更多的工作才能按照您想要的方式设置列表格式。

假设您的 csv 文件每行有六个整数,类似这样的内容可能会起作用:

import csv

list1 = []
with open('file1.csv', 'r') as f:
    reader = csv.reader(f)
    for line in reader:
        # split line into pairs of integers
        pairs = [(int(i), int(j)) for i, j 
                 in zip(line[0::2], line[1::2])]
        list1.append(pairs)

编辑:

@gregorio-pedullà 要求解释该行中使用的索引

pairs = [(int(i), int(j)) for i, j 
         in zip(line[0::2], line[1::2])]

在 Python 中对序列进行切片时,语法为 sequence[start:stop:step]。如果省略 stop,则切片将自动停止在序列末尾。

因此,line[0::2] 的意思是“从第一项(索引 0)开始,然后获取所有其他项,直到列表末尾。”简而言之,这将提取所有具有偶数索引的项目。

类似地,line[1::2] 表示“从第二个项目开始,并获取所有其他项目,直到列表末尾”。这将提取所有具有奇数索引的项目。

如果您想尝试一个示例,请运行以下命令:

example_list = [0, 1, 2, 3, 4, 5]

evens = example_list[0::2]
print(evens)
# [0, 2, 4]

odds = example_list[1::2]
print(odds)
# [1, 3, 5]

print(zip(evens, odds))
# [(0, 1), (2, 3), (4, 5)]

就您而言,您想从每行中提取整数对。在列表中创建连续项对的最简单方法之一是对偶数索引项和奇数索引项进行切片,然后 zip他们。

关于Python 从 CSV 创建嵌套列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56528142/

相关文章:

python - 在 Python 中使用日期时间的每月总金额

python - PythonRDD 的 rdd 和 ParallelCollectionRDD 有什么区别

python - 用 OpenGL 制作太阳系

python - Ursina 模块中的 invoke() 做了什么

python - 我在 python 中使用 pyttsx3 时收到 "member not found"错误

php - 使用 MySQL 直接从列的数据中获取列表

python - 无需设计器的实时推理管道

python - Tensorflow 可以进行条件计算吗?

Python版本/导入困惑

c++ - 允许用户在内部实现链表时与 std::strings 交互?