简体   繁体   中英

Error while working with construction try-except ValueError

result = []
try:
    for i in range(len(ass)):
        int(df['sku'][i])
except ValueError:
    result.append(df['sku'][i])

I need to collect all the errors in a list. Tell me, please, the code above adds only the first error, I need everything.

After iterating over all sku values, only those that cannot be converted to int should be included in the list.

You can move the try...except inside the loop:

result = []
for i in range(len(ass)):
    try:
        int(df['sku'][i])
    except ValueError:
        result.append(df['sku'][i])

You can also use isdigit() with a list comprehension as follows:

result = [val for val in df['sku'] if val.isdigit()]

However, you should note that isdigit() will not work in some cases eg those with leading signs.

As an example, '+1' will convert to an integer type fine with int() but will return False with is isdigit() . Similarly, -1 will convert fine with int() but return False with isdigit() .

Further information can be found int the documentation :

str.isdigit()

Return true if all characters in the string are digits and there is at least one character, false otherwise.

You'd want the try-except in the loop:

result = []
for i in range(len(ass)):
    try:
        int(df['sku'][i])
    except ValueError:
        result.append(df['sku'][i])

But if it's really a list of non-digit SKUs you want,

result = [sku for sku in df['sku'] if not sku.isdigit()]

This should work:

result = []
for i in range(len(ass)):
    try:
        int(df['sku'][i])
    except ValueError:
        result.append(df['sku'][i])

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