0
Unique element of tuple where tuple has list element
Hi I am trying to find out frequency of elements present into tuple. It works fine for me as per the code below: https://www.sololearn.com/compiler-playground/cFlQ1dF10TpW However, if tuple has list element (like tup = (1,2,[1,2,3],3,2), it does not work for obvious reason of list not allowed as key of dictionary. How to solve this problem ? Is there any other way ? https://code.sololearn.com/cFlQ1dF10TpW/?ref=app
9 ответов
+ 5
Ketan Lalcheta ,
(i hopefully have understood what you need)
> a common approach in a case like this could be to flatten the input object.
> this is a quite complex object with multiple level nesting:
nested_lst = ['hello',[1,3,0,[9,8],(1,5,'hello',0,0,[99],(1,2,3))]]
> what we should achieve as the first step is a *flat list* like:
['hello', 1, 3, 0, 9, 8, 1, 5, 'hello', 0, 0, 99, 1, 2, 3]
> when having done this, we can start an object counter using a dictionary.
> the result will be:
{'hello': 2, 1: 3, 3: 2, 0: 3, 9: 1, 8: 1, 5: 1, 99: 1, 2: 1}
+ 1
Set's element has to be immutable object. Since list is mutable it cannot be part of the set.
x = set(mutable object) will cause an error.
If you have a tuple and inside it has a list, you can use a for loop to look through each object, and then add the unique one into a list (or dictionary if you want).
+ 1
Ketan Lalcheta ,
I think your main problem is the idea of using a dictionary as a counter.
Use a different data structure. For example, a list of lists, with each sublist having two items, the first item being an item from the tuple (which could be any type including a list), and the second item being its frequency in the tuple.
In other words, it would have a structure similar to a dict, but without the mutability restrictions.
For example, this tuple,
tup = (
[1,2,3,2],
"Hello",
"Hello"
)
would produce this list of lists (I exploded it for readability).
[
[
[1, 2, 3, 2],
1
],
[
"Hello",
2
]
]
+ 1
+ 1
Lothar , i am sorry but that is difeerent than expectation.
Nice idea but ["hello",["hello",1],1] would not be a hello as 2.
+ 1
Rain nice approach. Worth trying. I am yet to try suggestions came out of this discussion. I am surely try. Once again thanks for nice suggestion.
+ 1
Nice tweak Bob_Li .
0
Let me try with list and for loop approach.
Dictionary is surely not working as key need to be mutable like set
0
When I said add into dictionary, I mean the key is 1, 2, 3, 4 and value is the unique element.