antonio_zeus antonio_zeus - 4 months ago 9
Python Question

python list - convert to list of list

I am hoping someone can point me in the right direction along with any documentation that can provide even more info than just the answer. Here we go, I have a list of strings:

arr = ["abcd","abcdef","def","abcdef"]


I want to turn that list into a list of lists so that the new element will be its order of appearance

arr = [("abcd",1),("abcdef",1),("def",1),("abcdef",2)]


the reason for this is because I would like to then sort that list by length of string, and in case any are of identical length, I can use the 2nd element of the list to know which one was first from my original list.

when "abcdef" appears twice, it also contains 1 or 2 in its 2nd element


hope that makes sense. thanks!

Answer

Simple and pythonic.

[(v, lst[:i].count(v)+1) for i,v in enumerate(lst)]

where lst is your list.

>>> lst = ["abcd","abcdef","def","abcdef"]
>>> [(v, lst[:i].count(v)+1) for i,v in enumerate(lst)]
[('abcd', 1), ('abcdef', 1), ('def', 1), ('abcdef', 2)]
Comments