【发布时间】:2021-09-29 13:23:27
【问题描述】:
我试图在 FOR 循环中从两个数据源输出值以显示在表中。我已经部分成功了,看起来是这样的:
| Customer | Product | Quantity | Customer | Product | Quantity |
|---|---|---|---|---|---|
| A001 | Product One | 3 | A001 | Product One | 3 |
| A003 | Product Two | 5 | A003 | Product Two | 3 |
| A010 | Product Three | 21 | A003 | Product Two | 2 |
| A007 | Product Four | 1 |
两个数据源的记录数可能不同,这就是我此时使用 zip_longest() 的原因,而且各个值可能会出现多次。为了更好地检测差异,我想做一个匹配并使输出看起来像这样 - 如果可能的话:
| Customer | Product | Quantity | Customer | Product | Quantity |
|---|---|---|---|---|---|
| A001 | Product One | 3 | A001 | Product One | 3 |
| A003 | Product Two | 5 | A003 | Product Two | 3 |
| A003 | Product Two | 2 | |||
| A010 | Product Three | 21 | |||
| A007 | Product Four | 1 |
是否可以在同一个循环中同时使用zip_longest() 和==?
for x, y in zip_longest(list_one, list_two, fillvalue=object()):
print(x[0])
print(x[1])
print(x[2])
print(y[0])
print(y[1])
print(y[2])
非常感谢。
【问题讨论】:
-
看起来您正在尝试使用重复键执行某些版本的
merge或join。也许考虑使用pandas? -
很遗憾,我还没有任何使用 pandas 的经验,但在这种情况下,我会朝那个方向做一些研究。感谢您的建议。
标签: python python-3.x loops for-loop