Python的怪异行为';s内置的max()方法
在使用Python的Python的怪异行为';s内置的max()方法,python,python-3.x,Python,Python 3.x,在使用Python的max()内置方法时,我发现了一件有趣的事情 input_one = u'A測試測試;B測試;測試;D測試測試測試;E測試測試測試測試測試測試測試測試測試' input_two = u'測試測試;測試;測試;測試測試測試;測試測試測試測試測試測試測試測試測試' input_en = u'test;test,test,test;testtesttest;testtesttesttest' input_ja = u'ああああああ;あああ;あああああああ;ああああああああああああ'
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()
但是,如果元素与符号混合(如@
#
$
),则其行为不同
比如说,
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版本是Python 3.4
这是我的问题还是我不知道的行为?好吧,你的test_length()
函数做的事情与max()
做的事情不同,max()
当给定的输入是字符串时,从输入返回按字典顺序排列的最大元素,而不是长度最大的元素
这是一个简单的例子-
>>> a = 'aaaaaaaaaa'
>>> b = 'b'
>>> max(a,b)
'b'
您的test\u length()
函数根据字符串的长度工作,这与max()
的作用不同
max()。在您的情况下,您可以传入len
以使max()
处理字符串的长度,例如-
>>> a = 'aaaaaaaaaa'
>>> b = 'b'
>>> max(a,b,key=len)
'aaaaaaaaaa'
考虑:
>>> max(['aaa','b','cc'])
'cc'
vs:
如果希望“max”使用字符串长度与字符串第一个字符的ascii码,请使用键函数——在本例中,使用内置的len
函数。我明白了。我去重读文件串了。发现我跳过了几行:(
>>> max(['aaa','b','cc'], key=len)
'aaa'