Nice programing

파이썬 슬라이스 방법, 파이썬 슬라이스를 알고 있지만 내장 슬라이스 객체를 어떻게 사용할 수 있습니까?

nicepro 2020. 11. 20. 09:35
반응형

파이썬 슬라이스 방법, 파이썬 슬라이스를 알고 있지만 내장 슬라이스 객체를 어떻게 사용할 수 있습니까?


내장 기능의 용도는 무엇 slice이며 어떻게 사용합니까?
내가 아는 Pythonic 슬라이싱의 직접적인 방법- l1[start:stop:step]. 슬라이스 객체가 있는지 알고 싶습니다. 어떻게 사용합니까?


[start : end : step] 표기법을 수행 할 때 사용하는 것과 동일한 필드로 slice를 호출하여 슬라이스를 만듭니다.

sl = slice(0,4)

슬라이스를 사용하려면 목록이나 문자열에 인덱스 인 것처럼 전달하면됩니다.

>>> s = "ABCDEFGHIJKL"
>>> sl = slice(0,4)
>>> print(s[sl])
'ABCD'

고정 길이 텍스트 필드 파일이 있다고 가정 해 보겠습니다. 이 파일의 각 "레코드"에서 값을 쉽게 추출하기 위해 조각 목록을 정의 할 수 있습니다.

data = """\
0010GEORGE JETSON    12345 SPACESHIP ST   HOUSTON       TX
0020WILE E COYOTE    312 ACME BLVD        TUCSON        AZ
0030FRED FLINTSTONE  246 GRANITE LANE     BEDROCK       CA
0040JONNY QUEST      31416 SCIENCE AVE    PALO ALTO     CA""".splitlines()


fieldslices = [slice(*fielddef) for fielddef in [
    (0,4), (4, 21), (21,42), (42,56), (56,58),
    ]]
fields = "id name address city state".split()

for rec in data:
    for field,sl in zip(fields, fieldslices):
        print("{} : {}".format(field, rec[sl]))
    print('')

인쇄물:

id : 0010
name : GEORGE JETSON    
address : 12345 SPACESHIP ST   
city : HOUSTON       
state : TX

id : 0020
name : WILE E COYOTE    
address : 312 ACME BLVD        
city : TUCSON        
state : AZ

id : 0030
name : FRED FLINTSTONE  
address : 246 GRANITE LANE     
city : BEDROCK       
state : CA

id : 0040
name : JONNY QUEST      
address : 31416 SCIENCE AVE    
city : PALO ALTO     
state : CA

시퀀스 뒤의 대괄호는 대괄호 안에 무엇이 있는지에 따라 인덱싱 또는 슬라이싱을 나타냅니다.

>>> "Python rocks"[1]    # index
'y'
>>> "Python rocks"[1:10:2]    # slice
'yhnrc'

Both of these cases are handled by the __getitem__() method of the sequence (or __setitem__() if on the left of an equals sign.) The index or slice is passed to the methods as a single argument, and the way Python does this is by converting the slice notation, (1:10:2, in this case) to a slice object: slice(1,10,2).

So if you are defining your own sequence-like class or overriding the __getitem__ or __setitem__ or __delitem__ methods of another class, you need to test the index argument to determine if it is an int or a slice, and process accordingly:

def __getitem__(self, index):
    if isinstance(index, int):
        ...    # process index as an integer
    elif isinstance(index, slice):
        start, stop, step = index.indices(len(self))    # index is a slice
        ...    # process slice
    else:
        raise TypeError("index must be int or slice")

A slice object has three attributes: start, stop and step, and one method: indices, which takes a single argument, the length of the object, and returns a 3-tuple: (start, stop, step).


>>> class sl:
...  def __getitem__(self, *keys): print keys
...     
>>> s = sl()
>>> s[1:3:5]
(slice(1, 3, 5),)
>>> s[1:2:3, 1, 4:5]
((slice(1, 2, 3), 1, slice(4, 5, None)),)
>>>

The slice function returns slice objects. Slice objects are one of Python's internal types, which are optimized for read performance - all of their attributes are read-only.

Altering slice could be useful if wish to change the default behaviour. For example, lxml uses slice notation to access DOM elements (however, I haven't confirmed how they did that myself).


While trying to answer Subset a string based on variable , I recalled that numpy has a syntactically nice way to define slice objects:

>>> import numpy as np
>>> s = "The long-string instrument is a musical instrument in which the string is of such a length that the fundamental transverse wave is below what a person can hear as a tone."
>>> z = np.s_[18:26]  # in this case same as slice(18, 26, None)
>>> s[z]
'strument'

The problem solved here is how to store the slice in a variable for later use, and np.s_ allows to do just that. Yes, it's not built-in, but as that original question was redirected here I feel like my answer belong here as well. Also, numpy was one of the reasons why so advanced slicing abilities were added to Python, IIRC.

An example of a more complex "slicing":

>>> data = np.array(range(6)).reshape((2, 3))
>>> z = np.s_[:1, 1:2]
>>> data[z]
array([[1]])
>>> data
array([[0, 1, 2],
       [3, 4, 5]])
>>> z
(slice(None, 1, None), slice(1, 2, None))

where z is now a tuple of slices.

참고URL : https://stackoverflow.com/questions/3911483/python-slice-how-to-i-know-the-python-slice-but-how-can-i-use-built-in-slice-ob

반응형