Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/309.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python字典和Openpyxl_Python_List_Dictionary_Openpyxl - Fatal编程技术网

Python字典和Openpyxl

Python字典和Openpyxl,python,list,dictionary,openpyxl,Python,List,Dictionary,Openpyxl,有人能给我解释一下以下代码的区别吗 我使用Openpyxl迭代*.XLSX文档(工作表C列)并从列表(列名称)返回单元格坐标 打印结果为C252,这是一个单元格坐标。这对我的应用程序正常运行 在下面的代码中,我尝试使用字典 def get_heading_coordinates(): range_dictionary = {'0': 'cell.offset(1, 0).coordinate', '1': 'cell.offset(-1, 0).coordinate'} for

有人能给我解释一下以下代码的区别吗

我使用Openpyxl迭代*.XLSX文档(工作表C列)并从列表(列名称)返回单元格坐标

打印结果为C252,这是一个单元格坐标。这对我的应用程序正常运行

在下面的代码中,我尝试使用字典

def get_heading_coordinates():
    range_dictionary = {'0': 'cell.offset(1, 0).coordinate', '1': 'cell.offset(-1, 0).coordinate'}
    for cell in ws['C']:
        if cell.value == str(column_names[1]):
            sec3_start = list(range_dictionary.values())[1]
    print(sec3_start)
打印的结果是cell.offset(-1,0)。坐标,据我所知是字典中的值。这对我的应用程序不正确。我要做的是分配变量'sec3_start'来检索单元格坐标,就像在第一个函数中一样

我试过:

  • range_dictionary.values()

  • range_dictionary.get(str(1))


我是否遗漏了一些明显的内容?

您的词典包含字符串。它打印字符串。它无法执行代码并获取您的值,因为它们是字符串,而不是函数。您应该做的是,例如,在dict中只存储
1
-1
(偏移值),并正常执行
cell.offset(range\u dictionary[key],0).coordinate)
。谢谢。我试图避免这样做,因为我有30个变量需要分配坐标,所以我更喜欢将它们存储在字典中。还有其他方法吗?你需要在那里存储一个函数,但这更复杂。您知道方法如何具有“参数”
self
?它通常是通过使用点之前的对象来“传递”的,对吗?但是您也可以执行
ClassName.method\u name(这里是object\u,parameter1,parameter2)
。这使它成为一个正常的函数,您可以在其中传递对象。因此,您可以执行lambda函数,该函数只接受在循环中变化的对象-
单元格
def get_heading_coordinates():
    range_dictionary = {'0': 'cell.offset(1, 0).coordinate', '1': 'cell.offset(-1, 0).coordinate'}
    for cell in ws['C']:
        if cell.value == str(column_names[1]):
            sec3_start = list(range_dictionary.values())[1]
    print(sec3_start)