python list - 转换为列表列表

时间:2016-08-05 01:19:24

标签: python list sorting indexing

我希望有人可以指出我正确的方向以及任何可以提供更多信息而不仅仅是答案的文档。我们走了,我有一个字符串列表:

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

我想将该列表转换为列表列表,以便新元素将是其出现顺序

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

原因是因为我想按字符串的长度对该列表进行排序,如果长度相同,我可以使用列表的第二个元素来知道哪一个是我的原始列表中的第一个

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

希望有道理。谢谢!

5 个答案:

答案 0 :(得分:4)

尝试以下for循环:

>>> arr = ["abcd","abcdef","def","abcdef"]
>>> counts = {}
>>> new = []
>>> for item in arr:
...     if item not in counts:
...             new.append((item, 1))
...             counts[item] = 1
...     else:
...             counts[item]+=1
...             new.append((item, counts[item]))
... 
>>> new
[('abcd', 1), ('abcdef', 1), ('def', 1), ('abcdef', 2)]
>>> 

答案 1 :(得分:3)

Python的排序是稳定的,每docs

  

sort()方法保证稳定。如果排序保证不改变比较相等

的元素的相对顺序,则排序是稳定的

所以只需将列表排序为@JulienBernu的删除答案:

onResume()

请注意,长度相等的项目仍保留原始顺序。您无需跟踪它。

答案 2 :(得分:0)

/health将完成这项工作。

答案 3 :(得分:0)

这看起来像是Counter

的工作
>>> from collections import Counter
>>> arr = ["abcd","abcdef","def","abcdef"]
>>> result = []
>>> current_count = Counter()
>>> for x in arr:
        current_count[x] += 1
        result.append( (x,current_count[x]) )

>>> result
[('abcd', 1), ('abcdef', 1), ('def', 1), ('abcdef', 2)]
>>> 

答案 4 :(得分:-1)

简单和pythonic。

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

其中lst是您的列表。

>>> 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)]