Python的内置max()方法的奇怪行为

2024-10-04 01:31:01 发布

您现在位置:Python中文网/ 问答频道 /正文

在使用Python的max()内置方法时,我发现了一件有趣的事情。。。。你知道吗

input_one = u'A測試測試;B測試;測試;D測試測試測試;E測試測試測試測試測試測試測試測試測試'
input_two = u'測試測試;測試;測試;測試測試測試;測試測試測試測試測試測試測試測試測試'
input_en = u'test;test,test,test;testtesttest;testtesttesttest'
input_ja = u'ああああああ;あああ;あああああああ;ああああああああああああ'
input_ja_mixed = u'aああああああ;bあああ;cあああああああ;dああああああああああああ'
input_ascii = u'egfwergreger;@#@$fgdfdfdfdsfsdfsdf;sdfsdfsfsdfs233'


def test_length(input):
    lengths = []
    for i in input:
        lengths.append(len(i))
    index = find_index(input, max(lengths))
    return input[index]


def find_index(input, to_find):
    for index, value in enumerate(input):
        print('index: %s, length: %s, value: %s' % (index, len(value), value))
        if len(value) == to_find:
            return index

def test_one(input):
    input = input.split(';')
    print('input:', input)
    print('using test_length: ', test_length(input))
    print('using max():', max(input))

如果使用max()在只包含英文字母的列表中查找max元素,效果会很好。你知道吗

但是,如果元素与符号混合(比如@#$),它的行为就不同了。你知道吗

例如

In [80]: test_one(input_ascii)
input: ['egfwergreger', '@#@$fgdfdfdfdsfsdfsdf', 'sdfsdfsfsdfs233']
index: 0, length: 12, value: egfwergreger
index: 1, length: 21, value: @#@$fgdfdfdfdsfsdfsdf
using test_length:  @#@$fgdfdfdfdsfsdfsdf
using max(): sdfsdfsfsdfs233

特殊情况是,中文和英文字母混在一起:

In [82]: test_one(input_one)
input: ['A測試測試', 'B測試', '測試', 'D測試測試測試', 'E測試測試測試測試測試測試測試測試測試']
index: 0, length: 5, value: A測試測試
index: 1, length: 3, value: B測試
index: 2, length: 2, value: 測試
index: 3, length: 7, value: D測試測試測試
index: 4, length: 19, value: E測試測試測試測試測試測試測試測試測試
using test_length:  E測試測試測試測試測試測試測試測試測試
using max(): 測試

文档没有指定max()方法具有的任何特殊行为。你知道吗

Python版本是python3.4。你知道吗

这是我的问题还是我不知道的?你知道吗


Tags: testinputindexvaluedeffindonelength
2条回答

好吧,你的test_length()函数做的事情与max()不同,max(),当给定的输入是字符串时,从输入中返回按字典顺序排列的最大元素,而不是长度最大的元素。你知道吗

一个简单的例子来说明这一点-

>>> a = 'aaaaaaaaaa'
>>> b = 'b'
>>> max(a,b)
'b'

test_length()函数根据字符串的长度工作,这与max()不同。你知道吗

max()还支持一个key参数,您可以将函数对象传递给该参数,该参数将用于确定哪个是输入中的最大元素。在您的例子中,可以传入len,使max()处理字符串的长度,例如-

>>> a = 'aaaaaaaaaa'
>>> b = 'b'
>>> max(a,b,key=len)
'aaaaaaaaaa'

考虑:

>>> max(['aaa','b','cc'])
'cc'

与:

>>> max(['aaa','b','cc'], key=len)
'aaa'

如果希望“max”使用字符串的长度与字符串第一个字符的ascii代码,请在本例中使用key函数和内置的len函数。你知道吗

相关问题 更多 >