Can we tie up the same elements in the Python list?

Asked 2 years ago, Updated 2 years ago, 42 views

If

["Ganada", "Ganada", "Ganada", "Ganada", "Ganada", "abc", "abc", "abc", "Mabasa", "Mabasa"]

When you have a one-dimensional list, such as With a two-dimensional list

["Ganada", "Ganada", "Ganada", "Ganada", "Ganada", ["abc"", "abc"], ["Mabasa", "Mabasa", "Mabasa"]]

Can I tie it like this?

list python

2022-09-21 10:06

3 Answers

from collections import Counter
l = ["Ganada", "Ganada", "Ganada", "Ganada", "Ganada", "abc", "abc", "Mabasa", "Mabasa"]
ll = [[k]*v for k, v in Counter(l).items()]

When you have time, study what python built-in module is available.
There's a lot of great functions.


2022-09-21 10:06

+Byeolhae

from itertools import groupby
l = ["Ganada", "Ganada", "Ganada", "Ganada", "Ganada", "abc", "abc", "Mabasa", "Mabasa"]
ll = [list(v) for _, v in groupby(l)]


2022-09-21 10:06

There are only answers using the module, so I will show you how to solve it with dictionary without having to import it separately.

a = ["Ganada"],Ganada"",Ganada"",Ganada"",Ganada"",abc"",Mabasa"",Mabasa"",Mabasa""
b = {}

for item in a:
    if item in b:
        b[item].append(item)
    else:
        b[item] = [item]

answer = list(b.values())


2022-09-21 10:06

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.