访问单个链接lis的特定元素

2024-05-13 02:13:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我想做一个函数get\ u element(n),根据元素在列表中的位置返回一个单链表的元素。如果我将-1发送给函数,我希望返回最后一个元素,如果是-2,函数将第二个返回给最后一个元素,依此类推。在不反转列表或引入其他属性(大小或类似属性)的情况下,如何做到这一点?如果我想从第二个到最后一个,我可以遍历列表直到当前。下一个。下一个==无,从第三个到最后一个当前。下一个。下一个.next==没有,但我不知道如何概括它。 如果有人能用任何一种语言给我写这段代码,我会很感激的,最好用Python。你知道吗


Tags: 函数代码语言元素列表get属性情况
1条回答
网友
1楼 · 发布于 2024-05-13 02:13:27

Python可能不是最好的语言,因为您想要的功能已经内置:

def get_element(n):
    my_list = ["The", "cat", "sat", "on", "the", "mat."]
    return my_list[n]


print get_element(0)
print get_element(-1)
print get_element(-2)

这将提供:

The
mat.
the

如前所述,您可以使用队列模拟问题:

import collections


def get_element(n):
    my_list = ["The", "cat", "sat", "on", "the", "mat."]

    if n >= 0:
        for index, element in enumerate(my_list):
            if index == n:
                return element

        # Return last element if beyond the range
        return element  
    else:
        queue = collections.deque(maxlen=-n)    # Used to simulate a queue

        for element in my_list:
            queue.append(element)

        return queue.popleft()


print get_element(0)
print get_element(-1)
print get_element(-2)

这将提供:

The
mat.
the

相关问题 更多 >