code

목록 인덱스가 있으면 X를 수행합니다.

starcafe 2023. 7. 7. 19:16
반응형

목록 인덱스가 있으면 X를 수행합니다.

내 프로그램에서 사용자가 번호를 입력합니다.n그리고 나서 입력.n목록에 저장되는 문자열 수입니다.

특정 목록 인덱스가 존재하면 함수를 실행하도록 코딩해야 합니다.

만약 내가 네스트를 했다면 이것은 더 복잡해집니다.len(my_list).

다음은 제가 지금 가지고 있는 것의 단순화된 버전이지만, 작동하지 않습니다.

n = input ("Define number of actors: ")

count = 0

nams = []

while count < n:
    count = count + 1
    print "Define name for actor ", count, ":"
    name = raw_input ()
    nams.append(name)

if nams[2]: #I am trying to say 'if nams[2] exists, do something depending on len(nams)
    if len(nams) > 3:
        do_something
    if len(nams) > 4
        do_something_else

if nams[3]: #etc.

당신이 목록의 길이를 사용하는 것이 더 유용할 수 있습니까?len(n)확인하는 것보다 당신의 결정을 알리는 것.n[i]가능한 각 길이에 대해?

특정 목록 인덱스가 존재하면 함수를 실행하도록 코딩해야 합니다.

이것은 시도 블록에 완벽하게 사용됩니다.

ar=[1,2,3]

try:
    t=ar[5]
except IndexError:
    print('sorry, no 5')   

# Note: this only is a valid test in this context 
# with absolute (ie, positive) index
# a relative index is only showing you that a value can be returned
# from that relative index from the end of the list...

그러나 정의에 따르면 파이썬 목록의 모든 항목은 다음과 같습니다.0그리고.len(the_list)-1존재(즉, 알고 있다면 시도 블록이 필요하지 않음)0 <= index < len(the_list)).

인덱스를 0에서 마지막 요소 사이에 두려면 열거형을 사용할 수 있습니다.

names=['barney','fred','dino']

for i, name in enumerate(names):
    print(i + ' ' + name)
    if i in (3,4):
        # do your thing with the index 'i' or value 'name' for each item...

하지만 정의된 '지표'를 찾고 있다면 잘못된 질문을 하고 있는 것 같습니다.매핑 컨테이너(예: 딕트)와 시퀀스 컨테이너(예: 목록)를 사용하는 것을 고려해야 합니다.다음과 같이 코드를 다시 작성할 수 있습니다.

def do_something(name):
    print('some thing 1 done with ' + name)
        
def do_something_else(name):
    print('something 2 done with ' + name)        
    
def default(name):
    print('nothing done with ' + name)     
    
something_to_do={  
    3: do_something,        
    4: do_something_else
    }        
            
n = input ("Define number of actors: ")
count = 0
names = []

for count in range(n):
    print("Define name for actor {}:".format(count+1))
    name = raw_input ()
    names.append(name)
    
for name in names:
    try:
        something_to_do[len(name)](name)
    except KeyError:
        default(name)

다음과 같이 실행:

Define number of actors: 3
Define name for actor 1: bob
Define name for actor 2: tony
Define name for actor 3: alice
some thing 1 done with bob
something 2 done with tony
nothing done with alice

짧은 버전을 제외하고 try/except 대신 .get 메서드를 사용할 수도 있습니다.

>>> something_to_do.get(3, default)('bob')
some thing 1 done with bob
>>> something_to_do.get(22, default)('alice')
nothing done with alice

다음 코드를 사용하여 간단히 수행할 수 있습니다.

if index < len(my_list):
    print(index, 'exists in the list')
else:
    print(index, "doesn't exist in the list")

len(nams)다음과 같아야 합니다.n당신의 코드로.모든 인덱스0 <= i < n"고집"

목록의 길이를 사용하는 것이 인덱스가 있는지 확인하는 가장 빠른 방법입니다.

def index_exists(ls, i):
    return (0 <= i < len(ls)) or (-len(ls) <= i < 0)

또한 음의 인덱스와 대부분의 시퀀스 유형을 테스트합니다(예:ranges그리고.str길이가 있는 것.

어차피 나중에 그 인덱스에서 항목에 액세스해야 한다면, 허용보다 용서를 구하는 것이 더 쉽고, 더 빠르고 더 파이썬적입니다.사용하다try: except:.

try:
    item = ls[i]
    # Do something with item
except IndexError:
    # Do something without the item

이는 다음과 반대됩니다.

if index_exists(ls, i):
    item = ls[i]
    # Do something with item
else:
    # Do something without the item

특정 목록 인덱스가 존재하면 함수를 실행하도록 코딩해야 합니다.

이미 테스트 방법을 알고 있으며 코드에서 이미 테스트를 수행하고 있습니다.

길이 리스트에 대한 유효한 인덱스n이다0통해.n-1포괄적인

따라서 목록에는 인덱스가 있습니다.i 목록의 길이가 최소한인 경우에만.i + 1.

삽입된 액터 데이터를 반복하려는 경우:

for i in range(n):
    if len(nams[i]) > 3:
        do_something
    if len(nams[i]) > 4:
        do_something_else

좋아요, 그래서 저는 (논쟁을 위해) 실제로 가능하다고 생각합니다.

>>> your_list = [5,6,7]
>>> 2 in zip(*enumerate(your_list))[0]
True
>>> 3 in zip(*enumerate(your_list))[0]
False

이런 것도 해볼 수 있어요.

list = ["a", "b", "C", "d", "e", "f", "r"]

for i in range(0, len(list), 2):
    print list[i]
    if len(list) % 2 == 1 and  i == len(list)-1:
        break
    print list[i+1];

한 줄기:

do_X() if len(your_list) > your_index else do_something_else()  

전체 예:

In [10]: def do_X(): 
    ...:     print(1) 
    ...:                                                                                                                                                                                                                                      

In [11]: def do_something_else(): 
    ...:     print(2) 
    ...:                                                                                                                                                                                                                                      

In [12]: your_index = 2                                                                                                                                                                                                                       

In [13]: your_list = [1,2,3]                                                                                                                                                                                                                  

In [14]: do_X() if len(your_list) > your_index else do_something_else()                                                                                                                                                                      
1

그냥 참고로.임호,try ... except IndexError더 나은 해결책입니다.

계산적으로 비효율적이지만 간단한 방법으로 오늘 이 문제를 해결하고 싶었습니다.

다음을 사용하여 my_list에 사용 가능한 인덱스 목록을 만듭니다.

indices = [index for index, _val in enumerate(my_list)]

그런 다음 각 코드 블록 앞에서 테스트할 수 있습니다.

if 1 in indices:
    "do something"
if 2 in indices:
    "do something more"

하지만 이것을 읽는 사람은 정말로 다음의 정답을 받아들여야 합니다: @user6039980.

브래킷 앞에 공간을 두지 마십시오.

예:

n = input ()
         ^

팁: 코드에 설명을 추가해야 합니다.당신 코드 뒤에는 없습니다.


좋은 하루 되세요.

언급URL : https://stackoverflow.com/questions/11786157/if-list-index-exists-do-x

반응형