首页 > 解决方案 > Python:如何将具有相同变量类型的多个列表合并到一个列表列表中?

问题描述

如何将三个列表列表组合成一个列表,以便第二级列表的第一个字符串出现在新列表列表的第一行和相应的第二个字符串中 - 在下一行(每个列表一行)?

假设有三个列表,如下所示:

[['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:请考虑行的长度不相等(第三个列表与前两个不同)。

标签: pythonpython-3.xlistmatrixrow

解决方案


您可以dictionary使用项目名称作为键将它们存储在 a 中,然后按字母顺序对它们进行排序并创建 a df,例如:

import pandas as pd


a = [['item_1', 'price_100'], ['item_2', 'price_200']] #from shop_a
b = [['item_1', 'price_120'], ['item_2', 'price_180']] #from shop_b
c = [['item_2', 'price_80'], ['item_3', 'price_220']] #from shop_c

data = {}
for item in a + b + c:
    item_name = item[0]
    item_price = item[1]
    item_data = data.get(item_name, ['', '', ''])
    item_data.append(item_price)
    item_data.pop(0)
    data[item_name] = item_data

sorted_rows = sorted([
    [item_data[0]]+item_data[1] for item_data in data.items()
], key=lambda item: item[0])

df = pd.DataFrame(sorted_rows, columns=['item_name', 'shop_a', 'shop_b', 'shop_c'])
print(df)

>>>
  item_name     shop_a     shop_b     shop_c
0    item_1             price_100  price_120
1    item_2  price_200  price_180   price_80
2    item_3                        price_220


推荐阅读