0

I have tried searching this and the closest thing I came was using Panda packages, however is there is a way to accomplish this simple groupby with only inbuilt modules

My example:

x = ['apples', 'cat', 'cherry' 'apples', 'cherry']

and when group, I want my end result to be:

y = ['apples', 'cat', 'cherry']
Red
  • 26,798
  • 7
  • 36
  • 58
Mattey
  • 69
  • 7
  • Your question is not clear enough. Your expected output suggests that you want to keep the strings in their order of appearance, but your comments under the answers that don't respect the order (all the ones converting your data to a set and back to a list) suggest otherwise. – Thierry Lathuille Nov 27 '20 at 17:04

3 Answers3

2

Maybe you could try list(set(x)).

I am assuming you intend to get unique values from a list, rather than "grouping" (which usually refers to a different concept).

This first converts the list into a set, which does not allow duplicates, then converts the result back to a list.

Kocas
  • 302
  • 1
  • 12
2

Maybe you can write your own method like

def group_array(yourlist):
   newlist=[]
   for i in yourlist:
      if i not in newlist:
         newlist.append(i)
   return newlist
batuhand
  • 475
  • 3
  • 11
1

Using a set() wrapper around your array will erase any duplicated elements:

x = ['apples', 'cat', 'cherry', 'apples', 'cherry']
y = list(set(x))
print(y)

Output:

['apples', 'cherry', 'cat']

If you want to keep the order of the strings (as sets are unordered), you can use a for loop:

x = ['apples', 'cat', 'cherry', 'apples', 'cherry']
y = []

for s in x:
    if s not in y:
        y.append(s)

print(y)

Output:

['apples', 'cherry', 'cat']
Red
  • 26,798
  • 7
  • 36
  • 58