我只是python的新手,我需要打印列表中包含最小和最大项目的列表。
例如,如果我有:
total_list = [[1, 2, 3], [1, 2, 3, 4], [1,2,3,4,5]]
我需要返回一个列表,列表的长度最小。我怎么能简单地以python的方式来做呢?
我尝试对其进行迭代,但是我所能收到的只是列表中每个项目的唯一len
输出必须为:
total_list[0] and total_list[2]
预先感谢
答案 0 :(得分:3)
max
和min
函数接受一个key
参数,该参数将根据定义为键的值找到可迭代的最大值。所以,试试这个:
max(total_list, key=len)
然后您可以使用total_list.index
查找这些索引
答案 1 :(得分:2)
total_list = [[1, 2, 3], [1, 2, 3, 4], [1,2,3,4,5]]
print('total_list[{0}] and total_list[{1}]'.format(total_list.index(min(total_list, key=len)), total_list.index(max(total_list, key=len))))
输出:
C:\Users\Desktop>py x.py
total_list[0] and total_list[2]
答案 2 :(得分:0)
使用min( iterable, key=len)
(min / max)最简单。如果您想自己浏览列表,可以这样做:
tl = [[1, 2, 3], [1, 2, 3, 4], [1,2,3,4,5]]
# init shortest and longest to 1st element of list
# use a tuple to store: ( listdata, length, position in original list )
shortest = longest = (tl[0], len(tl[0]), 0)
# iterate over remaining elements
for pos_act,act in enumerate(tl[1:],1): # start enumerate on 1 to fix position due slicing
# get actual length
len_act = len(act)
# is it larger then current largest?
if len_act > longest[1]:
longest = (act,len_act, pos_act)
# is it shorter then current shortest?
if len_act < shortest[1]:
shortest = (act, len_act, pos_act)
print ("Shortest: {} with len {} on position {}".format(*shortest))
print ("Longest: {} with len {} on position {}".format(*longest))
输出:
Shortest: [1, 2, 3] with len 3 on position 0
Longest: [1, 2, 3, 4, 5] with len 5 on position 2
Doku: