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



如何在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 中的倒数第二个值包含 101100(charlimit 中的值(,所以我希望它不仅打印

101100,"hello"

(就像目前的代码一样(

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

101100,"hello"
101101,"twenty"

感谢这里的任何帮助。请注意,response是一个很长的列表,因此如果可能的话,我希望使事情变得相当有效,尽管它在这项工作的背景下并不重要。我可能错过了一些非常简单的东西,但找不到任何人在不使用非常小的列表中使用特定索引的情况下执行此操作的示例。

您可以使用

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上的循环,而是循环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}

相关内容

最新更新