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

时间:2016-10-12 11:20:37

标签: python

我有一个元组列表:

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的新列表。第一个列表lst中的元组中的所有int都不会出现在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')]

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

3 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:1)

你的内心在这里是过分的。 而不是范围内的k(1,11):如果k> = 1且k <= 10,则应使用

答案 2 :(得分:1)

已有更好的答案,但只是为了向您展示如何修改您的循环以产生所需的结果:

for k in range(1,11):
  exists=False
  for tupl in lst:
    if tupl[0] == k:
      lst2.append((k, tupl[1]))
      exists = True
      break
  if not exists:
    lst2.append((k, ""))
print lst2