Python - 没有最后一个元素的列表

时间:2014-11-15 18:16:00

标签: python list loops tuples enumerate

我有一个元组列表,想要创建一个新列表。 使用新列表的最后一个元素(第一个元素为0)和旧列表的下一个元组的第二个元素计算新列表的元素。

要更好地理解:

list_of_tuples = [(3, 4), (5, 2), (9, 1)]  # old list
new_list = [0]
for i, (a, b) in enumerate(list_of_tuples):
  new_list.append(new_list[i] + b)

所以这是解决方案,但不必计算新列表的最后一个元素。所以不想要最后一个元素。

是否有一种创建新列表的漂亮方法? 到目前为止,我的解决方案是使用范围,但看起来并不那么好:

for i in range(len(list_of_tuples)-1):
  new_list.append(new_list[i] + list_of_tuples[i][1])

我是python的新手,所以感谢任何帮助。

1 个答案:

答案 0 :(得分:4)

您只需使用slice notation跳过最后一个元素:

for i, (a, b) in enumerate(list_of_tuples[:-1]):

以下是演示:

>>> lst = [1, 2, 3, 4, 5]
>>> lst[:-1]
[1, 2, 3, 4]
>>> for i in lst[:-1]:
...     i
...
1
2
3
4
>>>
相关问题