如何根据需求创建新的元组列表

时间:2019-07-01 11:31:52

标签: python-3.x list tuples

我有一个这样的元组列表:

list1 = [(pos.number, type, kind),
         (12, fruits, big-bananas), 
         (0, fruits, big-bananas), 
         (0, fruits, big-bananas), 
         (0, fruits, big-bananas), 
         (15, fruits, small-bananas), 
         (0, fruits, small-bananas), 
         (81, fruits, oranges),
         (0, fruits, oranges),
         (0, fruits, oranges),
         (93, fruits, kiwis)
        ]

每个元组都由位置编号,产品类型和产品种类组成。每种产品的首次出现都有独特的位置。数字,所有其他外观均使用0代替pos。数字

我想使用修改后的类型字段创建一个新的元组列表。我需要将相同种类的第一行设置为“水果优先”,最后一行为“水果最后”,中间的所有行都标记为“ fruits-med”。

这是所需的结果列表:

res = [(pos.number, type, kind), 
       (12, fruits-first, big-bananas), 
       (0, fruits-med, big-bananas), 
       (0, fruits-med, big-bananas), 
       (0, fruits-last, big-bananas), 
       (15, fruits-first, small-bananas), 
       (0, fruits-last, small-bananas), 
       (81, fruits-first, oranges),
       (0, fruits-med, oranges),
       (0, fruits-last, oranges),
       (93, fruits-first, kiwis)
      ]

我找到了一个丑陋的解决方案。

希望社区可以帮助改进它并使之更像“ Pythonic

current_kind = ""
current_product_list = []
new_product_list = []
for item in list1:
    if item[0] != 0 and current_kind == "":
        current_kind == "item[-1]"
        current_product_list.append(item)
    if item[-1] == current_kind:
        current_product_list.append(item)
    if item[0] != 0 and current_kind != "" and len(current_product_list) > 1:
        pos, type, kind = current_product_list.pop(0)
        new_product_list.append((pos, "fruits-first", kind))
        pos, type, kind = current_product_list.pop()
        new_product_list.append((pos, "fruits-last", kind))
        for line in current_product_list:
            pos, type, kind = line
            new_product_list.append((pos, "fruits-med", kind))
            current_product_list.pop()
        current_kind = item[-1]
        current_product_list.append(item)
print("New product list: ", new_product_list)

0 个答案:

没有答案