我正在尝试获取嵌套列表中包含的项的最大长度。这些最大长度值将用于创建数据库表。
获取嵌套列表中单个项目的最大长度的最佳方法是什么?
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)
答案 0 :(得分:1)
您的循环不会将不同的article_type值相互比较,因此您不会获得最大值。
尝试以下方法:
max(len(item[0]) for item in news_article_rows)
这会将每个值相互比较,因此会从所有值中获取实际的最大值。