在现有列表中创建最短和最长单词的新列表 - Python

时间:2015-03-05 11:58:17

标签: python list loops for-loop

我知道有更好的方法可以做到这一点,但我似乎无法找到它。正如你在下面看到的那样,我得到的是最长和最短的结果,但这只是因为我知道最长和最短的单词是什么,然后我输入了一个条件....但如果我不知道最长和最短的单词怎么办? ...希望我清楚自己。刚开始编程,所以没有任何经验。非常感谢您的帮助!

names = [ "Brian", "jake", "Jason", "Brad", "Tony", "jimmy", "Bobby", "Stevie"] 

long = []
short = []

for name in names:
    if len(name) <= 4:
        short.append(name)
        print "Short names: ", short

for name in names:
    if len(name) >=6:
        long.append(name)
        print "long names: ", long

3 个答案:

答案 0 :(得分:2)

您可以使用

找到最短和最长名称的len
len_short = min([len(x) for x in names])
len_long = max([len(x) for x in names])

然后,这些变量可以替换代码中的46


names = [ "Brian", "jake", "Jason", "Brad", "Tony", "jimmy", "Bobby", "Stevie"] 

long = []
short = []
len_short = min([len(x) for x in names])  # this will be 4
len_long = max([len(x) for x in names])  # this will be 6

for name in names:
    if len(name) <= len_short:
        short.append(name)
        print "Short names: ", short

for name in names:
    if len(name) >= len_long:
        long.append(name)
        print "long names: ", long

答案 1 :(得分:2)

您可以将maxmin内置函数与len用作key参数。

>>> names = [ "Brian", "jake", "Jason", "Brad", "Tony", "jimmy", "Bobby", "Stevie"]
>>> max(names, key=len)
'Stevie'
>>> min(names, key=len)
'jake'
>>> len(max(names, key=len))
6
>>> len(min(names, key=len))
4

答案 2 :(得分:0)

另一种方法是按名称长度对列表进行排序,然后过滤掉与最长和最短单词长度匹配的名称:

sorted_names = sorted(names, key=len)
short_names = [i for i in sorted_names if len(i) == len(sorted_names[0])]
long_names = [i for i in sorted_names if len(i) == len(sorted_names[-1])]