【问题标题】:Python - Go through list without last elementPython - 遍历没有最后一个元素的列表
【发布时间】:2015-01-12 23:19:27
【问题描述】:

我有一个元组列表并想创建一个新列表。 新列表的元素是用新列表的最后一个元素(第一个元素为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 新手,感谢任何帮助。

【问题讨论】:

  • new_list[i] 将失败,除非 new_list 与 list_of_tuples[:-1] 一样长

标签: python list loops tuples enumerate


【解决方案1】:

您可以简单地使用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
>>>

【讨论】:

    猜你喜欢
    • 2018-06-09
    • 2023-01-05
    • 2012-12-05
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 2012-06-13
    • 1970-01-01
    • 2021-07-17
    相关资源
    最近更新 更多