简体   繁体   中英

max length of items in list (python)

I'm trying to obtain the max length of an item contained in a nestled list. These max length values will be used in the creation of a database table.

What is the best method for obtaining the max length for individual items within a nestled list?

if len(news_article_rows) > 0:
  try:
    for item in news_article_rows:
      article_type = item[0]
      source_name = item[1]
      writer_name = item[2]
      article_href = item[3]
      topic_class = item[4]
      other_information = item[5]
      date_published = item[6]
      date_revised = item[7]

      max_length = max(article_type, key=len)
      print (max_length)

   except Exception as exception:
     traceback_str = ''.join(traceback.format_tb(exception.__traceback__))
     print(traceback_str)

Your loop doesn't compare the different article_type values against each other, so you're not getting the maximum.

Try this instead:

max(len(item[0]) for item in news_article_rows)

This compares every value against each other, so it gets the actual maximum out of all values.

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