简体   繁体   中英

Reformatting list in python

How to convert [a, a, a, b, b, b, c, c, c] > and so on, to [a,b,c,a,b,c,a,b,c,a,b,c] > and so on, in python?

Note, there can be also more than three same letters

You can use a combination of zip and itertools chain , groupby :

l = ['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c']
list(chain.from_iterable(zip(*(list(x) for _, x in groupby(l)))))
['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c']

As the problem is poorly described, I will make some assumptions. I will assume that each letter present in the input is present as many times as the others. Thus, the idea to create the output is to identify which unique letters are present in the input, and how many times. Moreover, I will assume that the input and output are list of strings. With that in mind, the following procedure works:

list_input = ['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c']
list_unique_elements = list(set(list_input))
list_count = list_input.count(list_unique_elements[0])
list_output = list_unique_elements*list_count

Output:

Out: ['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c']

You could do the following:

lst = ['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c']

d = {}
for e in lst:
    if e in d:
        d[e].append((len(d[e]), e))
    else:
        d[e] = [(0, e)]

result = sorted(value for values in d.values() for value in values)
result = [e[1] for e in result]

print(result)

Output

['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c']

Note : This solution is general in the sense that it does not needs the characters to be sorted, not to appear the same amount of times each.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM