您好,有一个 Excel 电子表格显示产品 ID 和位置,如下所示。
我想按顺序列出每个产品 ID 的所有位置,且不重复。
例如:
53424有凤凰城、松山、凤凰城、松山、凤凰城、松山、凤凰城。
56224 拥有博伊西三马林达。汉城。 等等
使用 Python 实现这一目标的最佳方法是什么?
我只能读取电子表格中的单元格,但不知道如何继续。
谢谢。
the_file = xlrd.open_workbook("C:\\excel file.xlsx")
the_sheet = the_file.sheet_by_name("Sheet1")
for row_index in range(0, the_sheet.nrows):
product_id = the_sheet.cell(row_index, 0).value
location = the_sheet.cell(row_index, 1).value
最佳答案
您需要利用Python的groupby()
删除重复项的函数如下:
from collections import defaultdict
from itertools import groupby
import xlrd
the_file = xlrd.open_workbook(r"excel file.xlsx")
the_sheet = the_file.sheet_by_name("Sheet1")
products = defaultdict(list)
for row_index in range(1, the_sheet.nrows):
products[int(the_sheet.cell(row_index, 0).value)].append(the_sheet.cell(row_index, 1).value)
for product, v in sorted(products.items()):
print "{} has {}.".format(product, ', '.join(k for k, g in groupby(v)))
这使用带有字典的 defaultlist()
来构建您的产品。因此,字典中的每个键都保存您的产品 ID,并且内容自动成为匹配条目的列表。最后,groupby()
用于读出每个原始值,并且仅在存在连续相同值的情况下为您提供一个条目。最后,生成的列表用逗号连接在一起。
关于Python读取Excel电子表格,根据变量和条件创建多个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42063801/