복붙노트

[PYTHON] Pythonic Circular List

PYTHON

Pythonic Circular List

목록이 있다고 해

l = [1, 2, 3, 4, 5, 6, 7, 8]

나는 임의의 요소의 인덱스와 그 이웃들의 값을 얻고 싶다. 예를 들어,

i = l.index(n)
j = l[i-1]
k = l[i+1]

그러나, i == len (l) - 1 인 edge case의 경우 이것은 실패합니다. 그래서 나는 그것을 단지 감쌀 것이라고 생각했다.

if i == len(l) - 1:
    k = l[0]
else:
    k = l[i+1]

이것을 할 파이썬 방법이 있습니까?

해결법

  1. ==============================

    1.모듈러스 연산자를 사용할 수 있습니다!

    모듈러스 연산자를 사용할 수 있습니다!

    i = len(l) - 1
    jIndex = (i - 1) % len(l)
    kIndex = (i + 1) % len(l)
    
    j = l[jIndex]
    k = l[kIndex]
    

    또는 덜 자세한 정보를 나타낼 수 있습니다.

    k = l[(i + 1) % len(l)]
    
  2. ==============================

    2.고정 길이 목록을 감싸는 가장 쉬운 방법은 % (모듈러스) 연산자를 사용하는 것입니다

    고정 길이 목록을 감싸는 가장 쉬운 방법은 % (모듈러스) 연산자를 사용하는 것입니다

    list_element = my_list[idx % len(my_list)]
    

    하지만 어쨌든 봐 http://docs.python.org/library/itertools.html

    from itertools import cycle
    
    for p in cycle([1,2,3]):
      print "endless cycle:", p
    
  3. ==============================

    3.특정 범위에 값을 맞추는 일반적인 방법은 % 연산자를 사용하는 것입니다.

    특정 범위에 값을 맞추는 일반적인 방법은 % 연산자를 사용하는 것입니다.

    k = l[(i + 1) % len(l)]
    
  4. ==============================

    4.수업을 원하면이 빠른 CircularList를 작성했습니다.

    수업을 원하면이 빠른 CircularList를 작성했습니다.

    import operator
    
    class CircularList(list):
        def __getitem__(self, x):
            if isinstance(x, slice):
                return [self[x] for x in self._rangeify(x)]
    
            index = operator.index(x)
            try:
                return super().__getitem__(index % len(self))
            except ZeroDivisionError:
                raise IndexError('list index out of range')
    
        def _rangeify(self, slice):
            start, stop, step = slice.start, slice.stop, slice.step
            if start is None:
                start = 0
            if stop is None:
                stop = len(self)
            if step is None:
                step = 1
            return range(start, stop, step)
    

    그것은 슬라이싱을 지원하므로

    CircularList(range(5))[1:10] == [1, 2, 3, 4, 0, 1, 2, 3, 4]
    
  5. ==============================

    5.당신이 감싸고 싶지 않을 경우에 대비해서, 가장 Pythonic 대답은 조각을 사용하는 것입니다. 없음으로 대체 된 누락 된 이웃. 예 :

    당신이 감싸고 싶지 않을 경우에 대비해서, 가장 Pythonic 대답은 조각을 사용하는 것입니다. 없음으로 대체 된 누락 된 이웃. 예 :

    def nbrs(l, e):
       i = l.index(e)
       return (l[i-1:i] + [None])[0], (l[i+1:i+2] + [None])[0]
    

    함수가 작동하는 방법은 다음과 같습니다.

    >>> nbrs([2,3,4,1], 1)
    (4, None)
    >>> nbrs([1,2,3], 1)
    (None, 2)
    >>> nbrs([2,3,4,1,5,6], 1)
    (4, 5)
    >>> nbrs([], 1)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<stdin>", line 2, in nbrs
    ValueError: 1 is not in list
    
  6. ==============================

    6.

    a = [2,3,5,7,11,13]
    
    def env (l, n, count):
        from itertools import cycle, islice
        index = l.index(n) + len(l)
        aux = islice (cycle (l), index - count, index + count + 1)
        return list(aux)
    

    다음과 같이 행동한다.

    >>> env (a, 2,1)
    [13, 2, 3]
    >>> env (a,13,2)
    [7, 11, 13, 2, 3]
    >>> env (a,7,0)
    [7]
    
  7. ==============================

    7.다른 사람들이 언급 한 모듈로 메서드를 사용하여 원형 목록을 구현하는 속성으로 클래스를 만들었습니다.

    다른 사람들이 언급 한 모듈로 메서드를 사용하여 원형 목록을 구현하는 속성으로 클래스를 만들었습니다.

    class Circle:
        """Creates a circular array of numbers
    
        >>> c = Circle(30)
        >>> c.position
        -1
        >>> c.position = 10
        >>> c.position
        10
        >>> c.position = 20
        >>> c.position
        20
        >>> c.position = 30
        >>> c.position
        0
        >>> c.position = -5
        >>> c.position
        25
        >>>
    
        """
        def __init__(self, size):
            if not isinstance(size, int):  # validating length
                raise TypeError("Only integers are allowed")
            self.size = size
    
        @property
        def position(self):
            try:
                return self._position
            except AttributeError:
                return -1
    
        @position.setter
        def position(self, value):
            positions = [x for x in range(0, self.size)]
            i = len(positions) - 1
            k = positions[(i + value + 1) % len(positions)]
            self._position = k
    
  8. from https://stackoverflow.com/questions/8951020/pythonic-circular-list by cc-by-sa and MIT license