dan*_*dee 6 python list nested-lists python-3.x
我有一个嵌套列表,我正在尝试获取总和并打印出具有最高数值的列表,当各个数字相加时
x = [[1,2,3],[4,5,6],[7,8,9]]
highest = list()
for i in x:
highest.append(sum(i))
for ind, a in enumerate(highest):
if a == max(highest):
print(x[ind])
Run Code Online (Sandbox Code Playgroud)
我已经能够打印出结果,但我认为应该有一种简单的Pythonic方式(可能使用列表理解).
我该怎么做?
mgi*_*son 13
怎么样:
print(max(x, key=sum))
Run Code Online (Sandbox Code Playgroud)
演示:
>>> x = [[1,2,3],[4,5,6],[7,8,9]]
>>> print(max(x, key=sum))
[7, 8, 9]
Run Code Online (Sandbox Code Playgroud)
这工作,因为max(连同其他一些巨蟒内建一样的min,sort...)接受用于比较的功能.在这种情况下,我只是说我们应该x根据他们的个人sum和Bob的叔叔来比较这些元素,我们已经完成了!
| 归档时间: |
|
| 查看次数: |
238 次 |
| 最近记录: |