【问题标题】:Get just the very next list within a nested list in python在python中获取嵌套列表中的下一个列表
【发布时间】:2018-04-07 18:37:01
【问题描述】:

如何在 python 的嵌套列表中获取下一个列表?

我有几个列表:

charLimit = [101100,114502,124602]

conditionalNextQ = [101101, 101200, 114503, 114504, 124603, 124604]`

response = [[100100,4]
,[100300,99]
,[1100500,6]
,[1100501,04]
,[100700,12]
,[100800,67]
,[100100,64]
,[100300,26]
,[100500,2]
,[100501,035]
,[100700,9]
,[100800,8]
,[101100,"hello"]
,[101101,"twenty"] ... ]

for question in charLimit:
    for limitQuestion in response:
        limitNumber = limitQuestion[0]
        if question == limitNumber:
            print(limitQuestion)

上面的代码正在做我想做的事,即当它包含charlimit 中的数字之一时,打印response 中的列表实例。但是,我也希望它也打印response 中的下一个值。

例如,response 中的倒数第二个值包含 101100charlimit 中的值)所以我希望它不仅可以打印

101100,"hello"

(就像代码现在所做的那样)

但下一个列表也是(并且只有下一个)

101100,"hello"
101101,"twenty"

在此先感谢您的任何帮助。请注意response 是一个非常长的列表,所以我希望尽可能让事情变得相当高效,尽管它在这项工作的背景下并不重要。我可能遗漏了一些非常简单的东西,但是如果不使用非常小的列表中的特定索引,就找不到任何人这样做的例子。

【问题讨论】:

  • 你可以试试enumerate,正如已经建议的那样;但是,我想知道您是否应该重新考虑您的数据结构。看起来charLimitconditionalNextQresponse 中的值是某种类型的 ID,您正在通过 response 寻找匹配的 ID。如果是这样,您的代码可能会使用更合适的数据结构大大简化(并且可能更快) - 例如,数据由这些 ID 键入的字典。
  • 感谢@FMc,这是第一种方法,尽管在数据中存在“主”ID 中包含多个 ID 的实例,实际上类似于 python 中的嵌套列表,但嵌套了 ID .它有点乱,但我可能会重新审视它:)

标签: python nested-lists


【解决方案1】:

您可以使用enumerate

例如:

charLimit = [101100,114502,124602]
conditionalNextQ = [101101, 101200, 114503, 114504, 124603, 124604]
response = [[100100,4]
,[100300,99]
,[1100500,6]
,[1100501,04]
,[100700,12]
,[100800,67]
,[100100,64]
,[100300,26]
,[100500,2]
,[100501,035]
,[100700,9]
,[100800,8]
,[101100,"hello"]
,[101101,"twenty"]]

l = len(response) - 1
for question in charLimit:
    for i, limitQuestion in enumerate(response):
        limitNumber = limitQuestion[0]
        if question == limitNumber:
            print(limitQuestion)
            if (i+1) <= l:
                print(response[i+1])

输出:

[101100, 'hello']
[101101, 'twenty']

【讨论】:

  • 这似乎不起作用...我只得到与以前一样匹配 charlimit 的结果
  • 抱歉,更正,我得到 IndexError: list index out of range
  • 更新了 sn-p。现在可以试试吗?
【解决方案2】:

我会消除charLimit 上的循环并改为循环response。在这个循环中使用enumerate 允许我们通过索引访问下一个元素,以防我们想要打印它:

for i, limitQuestion in enumerate(response, 1):
    limitNumber = limitQuestion[0]

    # use the `in` operator to check if `limitNumber` equals any
    # of the numbers in `charLimit`
    if limitNumber in charLimit:
        print(limitQuestion)

        # if this isn't the last element in the list, also
        # print the next one
        if i < len(response):
            print(response[i])

如果charLimit 很长,您应该考虑将其定义为set,因为集合比列表具有更快的成员资格测试:

charLimit = {101100,114502,124602}

【讨论】:

    猜你喜欢
    • 2022-10-12
    • 2018-03-23
    • 2015-04-26
    • 1970-01-01
    • 1970-01-01
    • 2023-03-26
    • 2017-10-02
    • 2023-03-29
    • 1970-01-01
    相关资源
    最近更新 更多