Python 由字符串组成的列表的max方法
我想知道,如果我编写以下代码,为什么结果是“4”:Python 由字符串组成的列表的max方法,python,Python,我想知道,如果我编写以下代码,为什么结果是“4”: lists = ['1','2','3','4'] print(max(lists)) lists.append(5) print(max(lists)) 我假设列表的max方法首先从str转换为int,然后在前几行中给出ints的max,但如果我尝试下一行,这似乎是不正确的。有人能解释一下吗?你可以试试这个: lists = ['1','2','3','4'] print(max(list(map(int, lists)))) list
lists = ['1','2','3','4']
print(max(lists))
lists.append(5)
print(max(lists))
我假设列表的max方法首先从str
转换为int
,然后在前几行中给出int
s的max,但如果我尝试下一行,这似乎是不正确的。有人能解释一下吗?你可以试试这个:
lists = ['1','2','3','4']
print(max(list(map(int, lists))))
lists.append(5)
print(max(list(map(int, lists))))
您的列表包含字符串,您正在追加一个整数 列表=['1','2','3','4',5]
TypeError: '>' not supported between instances of 'str' and 'int'
如果只有字符串或只有int的max将进行比较,因为'>'运算符将起作用。您需要将列表转换为所有字符串或所有整数
lists = [int(x) for x in lists] #by list comprehension
>>> max(lists) # lists= [1, 2, 3, 4, 5]
>>> 5
lists = [str(x) for x in lists]
>>> max(lists) # lists = ['1', '2', '3', '4', '5']
>>> '5'
如果您还没有看到列表理解,那么它可以做到这一点,但速度要快得多,只需一行代码
new_list = []
for x in lists:
x = int(x) #convert each individual term to integer objects
new_list.append(x)
lists = new_list
实际上,对于以下两种情况,它都不会给您
TypeError
返回'4'
:
list = ['1', '2', '3', '4']
list = ['1', '2', '3', '4', 5]
因为在python中比较对象时,str
总是>int
这就是为什么将'4'
作为最大值,因为它是字符串中的最高值
下面是一个例子来证明我的观点:
>print '1' > 5
True
>print '1' > '5'
False
这就产生了一个类型错误,因为你不能比较str和int。我明白了。非常感谢你@Usongyang不要忘记接受答案,这样其他人在搜索同一个问题时可以看到正确的答案:)