首页 > 解决方案 > 如何从 Excel 文件中的两个不同行值创建字典?

问题描述

如果我在 excel 文件中有两行:

比如说 a,b,c,d... 和另一行,其值为 100,121,98,09,100,45,... 两行的列数相同;我们如何在 python 中创建字典,通过从 xlsx 文件中读取...。键为 a,b,c,...在同一列的另一行中具有相应的值。

#to get the two rows
l1=[]
l2=[]
for x in [row1_num,row2_num]:
   cells=xl_sheet.row_slice(rowx=x,start_colx=20,end_colx=xl_sheet.ncols)
   for idx,cellobj in enumerate(cells):
       #based on the idx...should have a dictionary with values in row1 as keys
       #and row2 as values
       if(cell_obj.value is not None):
          if x==row1_num:
             l1.append(cell_obj.value)
          elif x==row2_num:
             l2.append(cell_obj.value)

dictionary=dict(zip(l1,l2))             

这是一个好方法吗?退出for循环时list1 l1也变空了吗?

标签: pythonxlrd

解决方案


你有一个很好的开始。为自己解决这个问题时,对我来说最困难的部分是弄清楚如何将行分块成对。

这里有两个解决这个问题的方法。第一个在概念上可能更容易看到发生了什么。然后我发现了一种非常巧妙的方法来使用itertools.zip_longest. 请参阅如何在 Python 3 中分块列表?

 import urllib.request
 import xlrd
 import itertools as it

 # Fake data stored on my Minio server.
 url = "https://minio.apps.selfip.com/mymedia/xlxs/fake_xl.xlxs"

 filepath, response = urllib.request.urlretrieve(url, "/tmp/test.xlxs")

 wb = xlrd.open_workbook(filepath)
 ws = wb.sheet_by_index(0)

 odd_rows, even_rows = it.tee(ws.get_rows()) # Get 2 iterables using itertools.tee
 row_pairs = ( # generator expression to "chunk the rows into groups of 2"
     [[cell.value for cell in row] for row in rows] # 2D list of values
     for rows in zip(
         it.islice(odd_rows, 0, ws.nrows, 2), # Use itertools.islice, odd
         it.islice(even_rows, 1, ws.nrows, 2), # even
     )
 )
 # zip is useful for "zipping" key value pairs together.
 print([dict(zip(*row_pair)) for row_pair in row_pairs])

 # Another way to chunk the rows into pairs is like this:

 print([
     dict(zip(*[[cell.value for cell in pair] for pair in pairs]))
     for pairs in it.zip_longest(*it.repeat(iter(ws.get_rows()), 2))
 ])

两者的输出:

[{'2a5de626':'算法','86ce99a2':'实现','e6b481ba':'适配器','bc85c996':'能力','4edfb828':'数组','05d79ce2':'定义', 'b9b5ae33':'知识库','f0da7366':'复杂性','39a48259':'方法','1ee95d9e':'策略'},{'01bc389d':'神经网络','d5d16b0c':'监控','d9fb3a8d':'安装','8c7a049f':'暂停','f3d9aa0e':'帮助台','d0e8d371':'范式','9e33f679':'复杂性','6354affc':'核心', '606c4eb6': '群件', '97741196': '策略'}, {'76ae32df': '算法','942654da':'任务组','462fa31b':'能力','584df007':'适配器','f6293960':'态度','afd8fa00':'知识库','4c5f2c49':'联盟','6d76c690':'协作','3018a22b':'解决方案','034f1bb2':'访问'}]


推荐阅读