program tip

Python에서 범위를 벗어난 인덱스에 대한 기본값 가져 오기

radiobox 2020. 10. 28. 07:58
반응형

Python에서 범위를 벗어난 인덱스에 대한 기본값 가져 오기


a=['123','2',4]
b=a[4] or 'sss'
print b

목록 인덱스가 범위를 벗어 났을 때 기본값을 얻고 싶습니다 (여기 :) 'sss'.

어떻게 할 수 있습니까?


"허가가 아니라 용서를 구하라"라는 파이썬 정신으로, 여기 한 가지 방법이 있습니다 :

try:
    b = a[4]
except IndexError:
    b = 'sss'

"용서가 아닌 허가를 구하라"라는 비 Python 정신으로 다음과 같은 또 다른 방법이 있습니다.

b = a[4] if len(a) > 4 else 'sss'

파이썬에서 아름다운 정신은 못생긴 것보다 낫다

슬라이스 및 압축 해제를 사용하는 코드 골프 방법 (4 년 전에 유효했는지 확실하지 않지만 Python 2.7 + 3.3에 있음)

b,=a[4:5] or ['sss']

래퍼 함수 나 try-catch IMHO보다 좋지만 초보자에게는 위협적입니다. 개인적으로 튜플을 풀면 list [#]보다 훨씬 섹시합니다.

포장을 풀지 않고 슬라이싱 사용 :

b = a[4] if a[4:] else 'sss'

또는이 작업을 자주해야하고 사전을 만들어도 괜찮다면

d = dict(enumerate(a))
b=d.get(4,'sss')

또 다른 방법:

b = (a[4:]+['sss'])[0]

고유 한 목록 클래스를 만들 수 있습니다.

class MyList(list):
    def get(self, index, default=None):
        return self[index] if len(self) > index else default

다음과 같이 사용할 수 있습니다.

>>> l = MyList(['a', 'b', 'c'])
>>> l.get(1)
'b'
>>> l.get(9, 'no')
'no'

다음과 같은 경우에 약간의 도우미 함수를 정의 할 수도 있습니다.

def default(x, e, y):
    try:
        return x()
    except e:
        return y

x유형의 예외가 발생하지 않는 한 함수의 반환 값을 반환합니다 e. 이 경우 값을 반환합니다 y. 용법:

b = default(lambda: a[4], IndexError, 'sss')

편집 : 지정된 하나의 예외 유형 만 포착하도록했습니다.

개선을위한 제안은 여전히 ​​환영합니다!


첫 번째 요소를 원하는 일반적인 경우에는 다음을 수행 할 수 있습니다.

next(iter([1, 2, 3]), None)

나는 이것을 필터링 한 후 목록을 "언 래핑"하는데 사용합니다.

next((x for x in [1, 3, 5] if x % 2 == 0), None)

또는

cur.execute("SELECT field FROM table")
next(cur.fetchone(), None)

try:
    b = a[4]
except IndexError:
    b = 'sss'

깔끔한 방법 (딕셔너리를 사용하는 경우에만 작동) :

b = a.get(4,"sss") # exact same thing as above

여기에 당신이 좋아할만한 또 다른 방법이 있습니다.

b = a.setdefault(4,"sss") # if a[4] exists, returns that, otherwise sets a[4] to "sss" and returns "sss"

I’m all for asking permission (i.e. I don’t like the tryexcept method). However, the code gets a lot cleaner when it’s encapsulated in a method:

def get_at(array, index, default):
    if index < 0: index += len(array)
    if index < 0: raise IndexError('list index out of range')
    return array[index] if index < len(a) else default

b = get_at(a, 4, 'sss')

Since this is a top google hit, it's probably also worth mentioning that the standard "collections" package has a "defaultdict" which provides a more flexible solution to this problem.

You can do neat things, for example:

twodee = collections.defaultdict(dict)
twodee["the horizontal"]["the vertical"] = "we control"

Read more: http://docs.python.org/2/library/collections.html


If you are looking for a maintainable way of getting default values on the index operator I found the following useful:

If you override operator.getitem from the operator module to add an optional default parameter you get identical behaviour to the original while maintaining backwards compatibility.

def getitem(iterable, index, default=None):
  import operator
  try:
    return operator.getitem(iterable, index)
  except IndexError:
    return default

If you are looking for a quick hack for reducing the code length characterwise, you can try this.

a=['123','2',4]
a.append('sss') #Default value
n=5 #Index you want to access
max_index=len(a)-1
b=a[min(max_index, n)]
print(b)

But this trick is only useful when you no longer want further modification to the list


Using try/catch?

try:
    b=a[4]
except IndexError:
    b='sss'

참고URL : https://stackoverflow.com/questions/2574636/getting-a-default-value-on-index-out-of-range-in-python

반응형