【发布时间】:2020-05-20 07:31:27
【问题描述】:
如何将三个列表列表合并为一个,以便第二级列表的第一个字符串出现在新列表列表的第一行和相应的第二个字符串 - 在下一行中(每个列表一行) ?
假设有三个列表,如下所示:
[['item_1', 'price_100'], ['item_2', 'price_200']] #from shop_a
[['item_1', 'price_120'], ['item_2', 'price_180']] #from shop_b
[['item_2', 'price_80'], ['item_3', 'price_220']] #from shop_c
我想将它们合并成一个列表,如下所示:
[['item_name', 'shop_a', 'shop_b', 'shop_c'], #should become the header of the DataFrame
['item_1', 'price_100', 'price_120', ''], #should become the 1st row of the DF
['item_2', 'price_200', 'price_180', 'price_80'], #should become the 2nd row of the DF
['item_3', '', '', 'price_220']] #should become the 3rd row of the DF
我们的想法是在每一行中获取同一商品的所有价格,以便从列表构造的 DataFrame 将代表一个方便的矩阵来比较不同商店的价格。
如何做到这一点?我将不胜感激任何建议...
PS:请考虑行的长度不相等(第三个列表与前两个不同)。
【问题讨论】:
-
到目前为止你尝试了什么?
-
@GPhilo 谢谢,但如果我按照这个问题的答案,我会得到:` shop_a shop_b shop_c 0 [item_1, price_100] [item_1, price_120] [item_2, price_80] 1 [item_2, price_200] [item_2, price_180] [item_3, price_220] `所以该解决方案要求行的长度相同,项目的顺序相同,但情况并非如此。
标签: python python-3.x list matrix row