从简单列表构建元组列表

时间:2013-10-29 10:21:30

标签: python list python-3.3

这就是我应该做的事情: 编写一个函数来获取用户的值列表L,并从中构建[(a1,b1),..(an,bn)]形式的元组列表,其中ai是原始列表的每个值,bi代表其在名单中的位置。

实施例: 对于L=[3,2,-1,7,3,5],函数应构建并返回[(3,1),(2,2),(-1,3),(7,4), (3,5),(5,6)]

这是我的代码:

a=input("Enter values separated by comas: ")
L=eval(a)
print(L)

1 个答案:

答案 0 :(得分:5)

使用enumerate和列表理解:

>>> L = [3, 2, -1, 7, 3, 5]
>>> [(x, i) for i, x in enumerate(L, 1)]
[(3, 1), (2, 2), (-1, 3), (7, 4), (3, 5), (5, 6)]

enumerate的帮助:

>>> help(enumerate)
Help on class enumerate in module __builtin__:

class enumerate(object)
 |  enumerate(iterable[, start]) -> iterator for index, value of iterable
 |  
 |  Return an enumerate object.  iterable must be another object that supports
 |  iteration.  The enumerate object yields pairs containing a count (from
 |  start, which defaults to zero) and a value yielded by the iterable argument.
 |  enumerate is useful for obtaining an indexed list:
 |      (0, seq[0]), (1, seq[1]), (2, seq[2]), ...