简体   繁体   中英

javascript to python array translation

We are working on a project where we are translating javaScript code into python. Everything is going pretty smoothly, except for this one line of code that has given us errors on multiple translations:

"primes" is an empty array BTW.

JavaScript:

 var primes = [];

 if(primes[primes.length - 1] > 3){...}

Python:

 primes = []

 if primes[len(primes) - 1] > 3:
      ......

This code works in javascript, however in Python we get an error. It seems as though we are trying to access an index of the list that doesn't exist.

This is the error:

TypeError: object of type 'int' has no len()

Does anyone have a workaround?

Python hasn't a safe get so you should change your code this way:

primes = []

if primes and primes[len(primes) - 1] > 3:
    ...

Even better, to get the last of the list you can use primes[-1]

primes = []

if primes and primes[-1] > 3:
    ...

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