brad carp
brad carp

Reputation: 11

How to return a nested list of frequency from a Python list?

From a list of cards - return a nested list of the cards with the same numbers and then the rest in a separate list.

EXAMPLE: ['6C', '7C', '7D', '8S', '6D']

returning [['7C', '7D'], ['6C','6D'], ['8S']]

I have attempted using a while loop, but cant figure it out.

Thank you!

Upvotes: 0

Views: 131

Answers (4)

suyash
suyash

Reputation: 337

Another approach without using itertools groupby.

l = ['6C', '7C', '7D', '8S', '6D']

result, temp = [], []

l = sorted(l, key=lambda x: x[0])

counter = l[0][0]


for i in l:
    if i[0] == counter:
        temp.append(i)

    else:
        result.append(temp)
        temp = [i]
        counter = i[0]

if temp:
    result.append(temp)

print(result)

Upvotes: 0

Devesh Kumar Singh
Devesh Kumar Singh

Reputation: 20490

One possible solution is to sort the list, then group the list using itertools.groupby, both by using the integer part of the string, and then grouping items with common integer elements together

from itertools import groupby
li = ['6C', '7C', '7D', '8S', '6D']

#Sort the list based on the integer part of the string
li = sorted(li, key=lambda x:int(x[0]))

#Group the list based on the integer part of the string
res = [list(group) for _, group in groupby(li, key=lambda x:int(x[0]))]
print(res)

The output will be

[['6C', '6D'], ['7C', '7D'], ['8S']]

Upvotes: 1

Fahim Ahmed
Fahim Ahmed

Reputation: 159

I know it's not an optimal solution but...

a = ['6C', '7C', '7D', '8S', '6D']
item = []
ls = []
for i in range(len(a)):
  if a[i][0] in ls:
    continue
  else:
    ls.append(a[i][0])
    temp = []
    temp.append(a[i])
    for j in range((i+1), len(a)):
      if a[i][0] == a[j][0]:
        temp.append(a[j])
      else:
        continue
    item.append(temp)
print(item)

Upvotes: 0

Underoos
Underoos

Reputation: 5190

Here. Try this.

from itertools import groupby
a = ['6C', '7C', '7D', '8S', '6D']
a.sort()
final_list = []
for i, j in groupby(a, key=lambda x:x[0]):
    final_list.append(list(j))
print(final_list)

Upvotes: 1

Related Questions