【问题标题】:Grab last iteration of a specific list in Python -- and only last specific item获取 Python 中特定列表的最后一次迭代——并且只获取最后一个特定项目
【发布时间】:2021-06-23 17:23:50
【问题描述】:

如何在 python 列表中获取与我的if 语句匹配的特定项目的最后一次迭代?

例如:

my_list = ["passed1", "passed2", "passed3", "vetoed"]
my_other_list = ["passed4", "passed5", "passed6", "vetoed"]

combo_list = []
combo_list.append(my_list)
combo_list.append(my_other_list)

desired_output_list = []

我如何获取“通过”的最终迭代并且仅获取通过的最终迭代?

for x in combo_list:
    ###Grab passed3 and passed6 and append to desired_output_list

【问题讨论】:

  • if "passed" == list[-1]?也不要将你的变量命名为list,因为你会隐藏内置类型
  • 首先,永远不要使用list关键字作为变量。 我如何获取“通过”的最终迭代和仅通过的最终迭代?。你可以使用list[:-1]
  • 列表没有迭代。
  • combo_list 不保留my_listmy_other_list 之间的区别;如您所知,原始列表可能是 []["passed1", "passed2", ..., "vetoed"],这似乎会改变您的预期结果。

标签: python list if-statement


【解决方案1】:

使用list comprehension 中的最后一项并将其附加到所需的输出列表中:

my_list = ["passed1", "passed2", "passed3", "vetoed"]
my_other_list = ["passed4", "passed5", "passed6", "vetoed"]

combo_list = []
combo_list.append(my_list)
combo_list.append(my_other_list)

desired_output_list = []
for lst in combo_list:
    matches = [item for item in lst if "passed" in item]
    if matches:
        desired_output_list.append(matches[-1])

print(desired_output_list)
# ['passed3', 'passed6']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-24
    • 1970-01-01
    • 1970-01-01
    • 2013-10-24
    • 2018-04-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多