How can I write a list like [1,2,2,3,3] from a list like [1,2,3,3] in Python?

Asked 1 years ago, Updated 1 years ago, 384 views

I have a list X with only the values for the following elements, and how do I write a list Y with one value for each element?

#Original List
X = [4, 4, 4, 4, 3, 3, 6, 6, 6, 6, 6, 6, 6, 2, 1, 3, 3, 3 ]

# Translated List
Y = [4,3,6,2,1,3]

I thought about it for two days and looked it up, but I didn't understand.
I'm thinking that I might use list inclusion.

If anyone understands, please let me know.
Thank you for your cooperation.

python python3

2022-12-22 02:14

3 Answers

If you want to treat the 3,3,3 that appears first and the 3,3,3 that appears later, you can use the itertools.groupby() and list inclusion in this article.
Grouping consecutive elements of the same value in the list in Python (itertools.groupby)

import it tools

X = [4, 4, 4, 4, 3, 3, 6, 6, 6, 6, 6, 6, 6, 2, 1, 3, 3, 3 ]
Y = [k for k, gin intertools.groupby(X)]
print(Y)


2022-12-22 05:58

You can also use unique_justsen from more_itertools.

from more_itertools import unique_justseen

X = [4, 4, 4, 4, 3, 3, 6, 6, 6, 6, 6, 6, 6, 2, 1, 3, 3, 3 ]
Y = [* unique_justseen(X)]

print(Y)

# [4, 3, 6, 2, 1, 3]


2022-12-22 06:23

Programming includes Set (set: no duplication) and OrderedSet (order holding set) and
meet the requirements of a questionTo do the OrderedSet in Python, it seems that you can do the following:

https://www.educative.io/answers/what-is-orderedset-in-python

 from sortedcollections import OrderedSet

x = [4, 4, 4, 4, 3, 3, 6, 6, 6, 6, 6, 6, 6, 2, 1, 3, 3, 3 ]

y = OrderedSet(x)

print(y)

If you don't need to keep the order, you should be able to do the following:

 x = [4, 4, 4, 4, 3, 3, 3, 6, 6, 6, 6, 6, 6, 2, 2, 1, 3, 3, 3 ]

y = set(x)

print(y)


2022-12-22 07:26

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.