-1

这就是我应该做的: 编写一个函数以从用户那里获取值 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)
4

1 回答 1

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]), ...
于 2013-10-29T10:23:02.837 回答