If list index exists, do X

前端 未结 12 791
清酒与你
清酒与你 2020-12-02 11:41

In my program, user inputs number n, and then inputs n number of strings, which get stored in a list.

I need to code such that if a certain

相关标签:
12条回答
  • 2020-12-02 12:09

    If you want to iterate the inserted actors data:

    for i in range(n):
        if len(nams[i]) > 3:
            do_something
        if len(nams[i]) > 4:
            do_something_else
    
    0 讨论(0)
  • 2020-12-02 12:11

    len(nams) should be equal to n in your code. All indexes 0 <= i < n "exist".

    0 讨论(0)
  • 2020-12-02 12:12

    ok, so I think it's actually possible (for the sake of argument):

    >>> your_list = [5,6,7]
    >>> 2 in zip(*enumerate(your_list))[0]
    True
    >>> 3 in zip(*enumerate(your_list))[0]
    False
    
    0 讨论(0)
  • 2020-12-02 12:12

    Do not let any space in front of your brackets.

    Example:

    n = input ()
             ^
    

    Tip: You should add comments over and/or under your code. Not behind your code.


    Have a nice day.

    0 讨论(0)
  • 2020-12-02 12:14

    I need to code such that if a certain list index exists, then run a function.

    This is the perfect use for a try block:

    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...
    

    However, by definition, all items in a Python list between 0 and len(the_list)-1 exist (i.e., there is no need for a try, except if you know 0 <= index < len(the_list)).

    You can use enumerate if you want the indexes between 0 and the last element:

    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...
    

    If you are looking for some defined 'index' thought, I think you are asking the wrong question. Perhaps you should consider using a mapping container (such as a dict) versus a sequence container (such as a list). You could rewrite your code like this:

    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)
    

    Runs like this:

    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
    

    You can also use .get method rather than try/except for a shorter version:

    >>> something_to_do.get(3, default)('bob')
    some thing 1 done with bob
    >>> something_to_do.get(22, default)('alice')
    nothing done with alice
    
    0 讨论(0)
  • 2020-12-02 12:18

    Oneliner:

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

    Full example:

    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
    

    Just for info. Imho, try ... except IndexError is better solution.

    0 讨论(0)
提交回复
热议问题