在Python中,如何为列表中每个连续的重复元素赋值?

2024-06-17 12:59:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我有下面的情景

list1=['10/22/2017 10:00','10/22/2017 10:00','10/22/2017 10:00',
       '10/22/2017 11:00','10/22/2017 11:00','10/22/2017 11:00',
       '10/22/2017 12:00','10/22/2017 12:00','10/22/2017 12:00',
        ....
      ]
list2 = [1,2,5,4,5,3,3,5,6,......] #(list2 size will be equal to no. of unique elements of list1)

我的问题是如何显示具有如下值的list3

list3=[1,1,1,
       2,2,2,
       5,5,5,
       ...]

表示list1的连续重复元素数,每个list2元素应多次追加到list3中


Tags: oftono元素sizeequalelementsbe
3条回答

您可以使用itertools

import itertools
list1=['10/22/2017 10:00','10/22/2017 10:00','10/22/2017 10:00',
   '10/22/2017 11:00','10/22/2017 11:00','10/22/2017 11:00',
   '10/22/2017 12:00','10/22/2017 12:00','10/22/2017 12:00']
list2 = [1,2,5,4,5,3,3,5,6]
convert = {}
for a, b in zip(list1, list2):
   if a not in convert:
      convert[a] = b

new_data = list(itertools.chain(*[[convert[a] for c in range(len(list(b)))] for i, [a, b] in enumerate(itertools.groupby(list1))]))

输出:

[1, 1, 1, 4, 4, 4, 3, 3, 3]

您可以使用^{}来实现这一点

from itertools import groupby

list1 = ['a', 'a', 'a', 'b', 'c', 'c']
list2 = [1, 2, 5]

sum(([i] * len(list(g)) for (k, g), i in zip(groupby(list1), list2)), [])
# [1, 1, 1, 2, 5, 5]

它将list1分组成相等元素的块(实际上这些块本身就是[key,chunk generator]对),将这些块与list2中相应的项进行压缩,并使用块的长度和list2中的项来组装最终的列表,使用旧的sum(lists, [])技巧,这并不是整平列表的最佳方法,但非常简洁。如果性能很重要,请使用嵌套理解:

[x for l in ((i for _ in g) for (_, g), i in zip(groupby(list1), list2)) for x in l]

也可以使用collections.Counter()

import from collections import Counter
list1 = [...]
list2 = [...]

list1_counts = Counter(list1)
# list1_counts is now a dict of {uniqueitem: num_of_occurences}

list2_iter = iter(list2)

list3 = []

for u in list1_counts:
    # for each unique item in list1
    c2 = next(list2_iter) # pick the next value in list2
    list3.extend([c2 for _ in range(list1_counts[u])])

请注意,这并不一定保留list1中唯一项的出现顺序

相关问题 更多 >