Creating a tuple without using tuple function

Question:

I have to create a list of tuples without using the tuple() function. The input is a list of lists where each list contains a profile ID and the calendar date on which the user went of a date. The output is a list of tuples showing the profile ID and the number of dates the user went on.

The final output should be a list of tuples, but my code outputs each element individually.
Below is the code I wrote to try to convert the list elements to tuples.

for stuff in datingTrack:
        for smallerStuff in stuff:
            tuplesList = (smallerStuff)
            datingTrack2.append(tuplesList)
input: [["B111", "10/2/2022"], ["B222", "9/25/2022"], ["B333", "8/1/2022"], ["B222", "9/2/2022"]]

my output: ['B111', 1, 'B222', 2, 'B333', 1]

Expected output: [('B111', 1,) ('B222', 2), ('B333', 1)]
Asked By: Sara

||

Answers:

You can get the expected output with collections.Counter:

from collections import Counter

lst = [
    ["B111", "10/2/2022"],
    ["B222", "9/25/2022"],
    ["B333", "8/1/2022"],
    ["B222", "9/2/2022"],
]

c = Counter(v for v, _ in lst)
print(list(c.items()))

Prints:

[('B111', 1), ('B222', 2), ('B333', 1)]

EDIT: Solution without Counter:

lst = [
    ["B111", "10/2/2022"],
    ["B222", "9/25/2022"],
    ["B333", "8/1/2022"],
    ["B222", "9/2/2022"],
]

out = {}
for v, _ in lst:
    out[v] = out.get(v, 0) + 1

out = list(out.items())
print(out)

Prints:

[('B111', 1), ('B222', 2), ('B333', 1)]
Answered By: Andrej Kesely

EDIT: This does not answer the question. Please refer to the answers above


If you’re forced to not use the tuple construtor, this will do it

my_input = [["B111", "10/2/2022"], ["B222", "9/25/2022"], ["B333", "8/1/2022"], ["B222", "9/2/2022"]]

my_output = [(*item,) for item in my_input]
# [('B111', '10/2/2022'), ('B222', '9/25/2022'), ('B333', '8/1/2022'), ('B222', '9/2/2022')]
Answered By: MoonMist

This one almost does what you want:

datingTrack = [["B111", "10/2/2022"], ["B222", "9/25/2022"], ["B333", "8/1/2022"], ["B222", "9/2/2022"]]

dt2 = [(ID,len ([i for [i,j] in datingTrack if i==ID])) for (ID,date) in datingTrack]

Almost, because there will be multiple identical entries.
But that can be solved with:

dt2 = list(set(dt2))
Answered By: Swifty
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.