简体   繁体   中英

How to check if there is an entry that exists in an array/list in Python?

My code is assigning values to names out of a list. I need to know how to retrieve or set a default value if there is not an entry in my list to assign to one of the names. My code so far:

array =[[a],[b],[c],[d]]
no1 = array[0]
no2 =array[1]
no3 =array[2]
no4 =array[3]
# if array[4] exists:
    no5 = array[4]
else
    no5 = 0

I tried-

try:
    array[4]
except ValueError:
    no5 = 0

but it came up as array[4] out of range.

Just to clarify, as my code writing isn't spectacular, basically I am being given three different inputs for a program which should read these inputs and then write the outputs to a file. The problem is that all of the inputs have varying array lengths. So what I'm trying to do is somehow get the program to check if there is an entry for (say) array[4] and if that entry doesn't exist, create entry array[4] and make it equal to zero.

That you went to try and / except is good. If you got an IndexError then you're really close, you just caught the wrong type of error in your except . This would've worked:

try:
    no5 = array[4]
except IndexError:
    no5 = 0

您应该捕获IndexError (由array[4]引发的实际错误)而不是ValueError

instead of try you can also check the length of the array

def: elem_exists(arr, idx):
   return 0 <= ldx < len(arr)

You are trying to catch the wrong exception type

try:
    no5 = array[4]
except IndexError:
    no5 = 0

A nifty one-line solution for this is to use itertools

import itertools
(no1,no2,no3,no4,no5),_ = zip(*itertools.izip_longest(array[:5],range(5),fillvalue=0))

Why not something like the following?

if len(array) > 4:
    no5 = array[4]
else:
    no5 = 0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM