Python:你能读取单元格中的列表吗?

2024-06-11 03:03:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我想使用pygame为我的平板成型器读取csv文件单元格中的列表。 问题是,当我试图读取保存在单元格中的列表时,它将其解释为str而不是列表。这个列表是沿着[pygame.Rect(0, 750, 800, 50),...]这条线排列的。 我想把每个列表放在单元格而不是列中,因为每个级别都有多个这样的列表,长度不同

是否可以读取单元格内的列表/将其解释为一个列表,而不必用数据填充整列的单元格


Tags: 文件csv数据rect列表级别pygame成型
1条回答
网友
1楼 · 发布于 2024-06-11 03:03:51

我同意@juanpa.arrivillaga在评论中所说的话,但如果你坚持,你可以尝试以下方式:

import pandas as pd
from ast import literal_eval
import re
from io import StringIO


# pretend to be pygame.Rect
class MockRect:
    def __init__(self, left, top, width, height):
        self.left, self.top, self.width, self.height = left, top, width, height

    def __repr__(self):
        return f'pygame.Rect({self.left}, {self.top}, {self.width}, {self.height})'


# to change the string representation of our list of Rects to a string representation of a list of tuples
pattern = re.compile(r'pygame.Rect(\(\d+, \d+, \d+, \d+\))')


# to get back our list of Rects
def to_Rects(rects):
    s = pattern.sub(r'\g<1>', rects)
    arr = literal_eval(s)

    return [MockRect(*tup) for tup in arr]


# create our test DataFrame
d = {
    'id': [100, 101],
    'rects': [[MockRect(0, 0, 100, 50),
               MockRect(0, 50, 100, 50)],
              [MockRect(20, 0, 100, 50),
               MockRect(20, 20, 100, 50)]],
}
df = pd.DataFrame(d)
print(df)

# create our CSV
b = StringIO()
df.to_csv(b, index=False)
print(b.getvalue())

# read back our CSV
b.seek(0)
df = pd.read_csv(b)

# get back our list of Rects
df.rects = df.rects.apply(to_Rects)
print(df)

相关问题 更多 >