Skip to main content
 首页 » 编程设计

python list之转换为列表列表

2025年05月04日16yjmyzz

我希望有人能为我指出正确的方向以及任何可以提供比答案更多信息的文档。我们开始吧,我有一个字符串列表:

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 

希望这是有道理的。谢谢!

请您参考如下方法:

尝试以下 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)] 
>>>