Python读取Excel电子表格,根据变量和条件创建多个列表

标签 python excel list

您好,有一个 Excel 电子表格显示产品 ID 和位置,如下所示。

enter image description here

我想按顺序列出每个产品 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/

相关文章:

python - 日期字符串到时间元组

python - 如何快速有效地检查图像是否主要是背景?

python - 在 Python 中添加到字典时可以连接一个值吗?

excel - 在 Excel 工作表名称中使用井号 (#)

python - 在元组中强制元组?

R覆盖另一个列表中的列表值

python - 如何阻止 Pepper 机器人抢占其平板电脑?

excel - 在VBA中绘制箭头超出范围

python - 比较两个电子表格并提取值

python - 根据空字符串切片 python 列表