📌  相关文章
📜  Python - 字符串整数列表的最大值

📅  最后修改于: 2022-05-13 01:54:29.669000             🧑  作者: Mango

Python - 字符串整数列表的最大值

有时,在处理数据时,我们可能会遇到一个问题,即我们收到一系列包含字符串格式数据的列表,我们希望找到每个字符串列表整数的最大值。让我们讨论可以执行此任务的某些方式。
方法 #1:使用循环 + int()
这是执行此任务的蛮力方法。在此,我们为整个列表运行一个循环,将每个字符串转换为整数并按列表执行最大化并存储在单独的列表中。

Python3
# Python3 code to demonstrate working of
# Maximum of String Integer
# using loop + int()
 
# initialize list
test_list = [['1', '4'], ['5', '6'], ['7', '10']]
 
# printing original list
print("The original list : " + str(test_list))
 
# Maximum of String Integer
# using loop + int()
res = []
for sub in test_list:
    par_max = 0
    for ele in sub:
        par_max = max(par_max, int(ele))
    res.append(par_max)
 
# printing result
print("List after maximization of nested string lists : " + str(res))


Python3
# Python3 code to demonstrate working of
# Maximum of String Integer
# using max() + int() + list comprehension
 
# initialize list
test_list = [['1', '4'], ['5', '6'], ['7', '10']]
 
# printing original list
print("The original list : " + str(test_list))
 
# Maximum of String Integer
# using max() + int() + list comprehension
res = [max(int(ele) for ele in sub) for sub in test_list]
 
# printing result
print("List after maximization of nested string lists : " + str(res))


输出 :
The original list : [['1', '4'], ['5', '6'], ['7', '10']]
List after maximization of nested string lists : [4, 6, 10]


方法 #2:使用 max() + int() + 列表理解
这是可以执行此任务的简写。在此,我们使用列表推导在列表上运行一个循环,并使用 max() 提取最大化。

Python3

# Python3 code to demonstrate working of
# Maximum of String Integer
# using max() + int() + list comprehension
 
# initialize list
test_list = [['1', '4'], ['5', '6'], ['7', '10']]
 
# printing original list
print("The original list : " + str(test_list))
 
# Maximum of String Integer
# using max() + int() + list comprehension
res = [max(int(ele) for ele in sub) for sub in test_list]
 
# printing result
print("List after maximization of nested string lists : " + str(res))
输出 :
The original list : [['1', '4'], ['5', '6'], ['7', '10']]
List after maximization of nested string lists : [4, 6, 10]