在列表中编辑和重新排序元组

克里斯

我有一个元组列表:

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的新列表。第一个列表中元组中所有intlst都不会出现在1到10范围内的int将在新列表中产生一个空字符串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)]

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章