美好的一天。Excel 电子表格中有一些数据,结构如下:
它希望将 3 列中的唯一值放在一起,很好地形成如下格式:
Mike to America for Hotel; Meal
和
Kate to Europe; America for Transport
等等
我只能锻炼 2 列。
the_file = xlrd.open_workbook("testing.xlsx")
the_sheet = the_file.sheet_by_name("Sheet1")
products = defaultdict(list)
for row_index in range(1, the_sheet.nrows):
products[str(the_sheet.cell(row_index, 0).value)].append(the_sheet.cell(row_index, 1).value)
for product, v in products.items()
print product + " to " + ";".join(set(v))
输出是:
Mike to America
Hulk to America;Asia
Kate to Europe;America
Dave to Europe
Jack to Europe;America;Asia
Luci to Asia
使线条同时为 3 列工作的方法是什么?
谢谢你。
认为有一种更pythonic的方式来做到这一点,但这就是我想出的:
from collections import defaultdict
l = [
['mike', 'america', 'hotel'],
['mike', 'america', 'meal'],
['jack', 'america', 'meal'],
['jack', 'europe', 'hotel'],
['jack', 'america', 'bonus'],
['jack', 'asia', 'hotel'],
['dave', 'europe', 'meal'],
]
people = defaultdict(list)
people_places = defaultdict(list)
for row_index in range(len(l)):
people[l[row_index][0]].append(l[row_index][1])
people_places[l[row_index][0] + '|' + l[row_index][1]].append(l[row_index][2])
for p, k in people.items():
activity = []
for place in k:
activity += people_places[p + '|' + place]
print '{} to {} for {}'.format(
p,
';'.join(set(k)),
';'.join(set(activity))
)
您可以将代码转换为直接使用电子表格行和单元格,或者l
首先使用以下内容提取列表:
l = []
with xlrd.open_workbook("testing.xlsx") as the_file:
the_sheet = the_file.sheet_by_name("Sheet1")
for row_index in range(1, the_sheet.nrows):
l.append([
the_sheet.cell(row_index, 0).value,
the_sheet.cell(row_index, 1).value,
the_sheet.cell(row_index, 2).value])
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句