Skip to main content
 首页 » 编程设计

python之编辑和重新排序列表中的元组

2025年05月04日14pengyingh

我有一个元组列表:

lst = [(1, "text"), (2, "more"), (5, "more"), (10, "more")] 

元组的结构为(int, string),从 1 开始,最大值为 10。我想将它们编辑并重新排序为:

lst2 = [(1, "text"), (2, "more"), (3, ""), (4, ""), (5, "more"), (6, ""), (7, ""), (8, ""), 
       (9, ""), (10, "more")] 

如您所见,我想创建一个连续编号为 10 的新列表。所有 int 来自第一个列表 lst 中的元组,不在 1 到10 将在新列表 lst2 中生成一个空字符串。

我想出了这段代码:

lst2 = [] 
for tupl in lst: 
  for k in range(1,11): 
    if tupl[0] == k: 
      lst2.append((k, tupl[1])) 
    else: 
      lst2.append((k, "")) 
print lst2 

但是结果很奇怪:

[(1, 'text'), (2, ''), (3, ''), (4, ''), (5, ''), (6, ''), (7, ''), (8, ''), (9, ''), 
(10, ''), (1, ''), (2, 'more'), (3, ''), (4, ''), (5, ''), (6, ''), (7, ''), (8, ''), 
(9, ''), (10, ''), (1, ''), (2, ''), (3, ''), (4, ''), (5, 'more'), (6, ''), (7, ''), 
(8, ''), (9, ''), (10, ''), (1, ''), (2, ''), (3, ''), (4, ''), (5, ''), (6, ''), (7, ''), 
(8, ''), (9, ''), (10, 'more')] 

任何人都可以帮助我或告诉我我做错了什么吗?谢谢。

请您参考如下方法:

lst = [(1, "text"), (2, "more"), (5, "more"), (10, "more")] 
d = dict(lst) 
lst2 = [(i, d.get(i, "")) for i in range(1, 11)] 

编辑

或者,使用 defaultdict :

lst = [(1, "text"), (2, "more"), (5, "more"), (10, "more")] 
from collections import defaultdict 
d = defaultdict(str, lst) 
lst2 = [(i, d[i]) for i in range(1, 11)]