Python 列表的计算?
Calculations on Python lists?
我有这个列表:
[[54.1757, 57.7807], [61.5786, 64.1535], [67.9584, 83.0], [104.4185, 120.377]]
我想做的是将这个列表翻译成我有字符串的格式:
first_number:second_number-first_number
对于我列表中的每一对。所以对于第一对,我会得到以下字符串:
"54.1757:3.605"
关于最佳实施方式的任何建议?
您可以使用 list comprehension:
In [1]: arr = [[54.1757, 57.7807], [61.5786, 64.1535], [67.9584, 83.0], [104.4185, 120.377]]
In [2]: arr2 = [ "{}:{}".format(a, a-b) for a, b in arr ]
In [3]: arr2
Out[3]:
['54.1757:-3.605', '61.5786:-2.5749', '67.9584:-15.0416', '104.4185:-15.9585']
使用列表理解很容易做到这一点。
>>> list = [[54.1757, 57.7807], [61.5786, 64.1535], [67.9584, 83.0], [104.4185, 120.377]]
>>>
>>> [ {x:y-x} for x, y in list ]
[{54.1757: 3.605000000000004}, {61.5786: 2.5748999999999924}, {67.9584: 15.041600000000003}, {104.4185: 15.9585}]
>>>
我有这个列表:
[[54.1757, 57.7807], [61.5786, 64.1535], [67.9584, 83.0], [104.4185, 120.377]]
我想做的是将这个列表翻译成我有字符串的格式:
first_number:second_number-first_number
对于我列表中的每一对。所以对于第一对,我会得到以下字符串:
"54.1757:3.605"
关于最佳实施方式的任何建议?
您可以使用 list comprehension:
In [1]: arr = [[54.1757, 57.7807], [61.5786, 64.1535], [67.9584, 83.0], [104.4185, 120.377]]
In [2]: arr2 = [ "{}:{}".format(a, a-b) for a, b in arr ]
In [3]: arr2
Out[3]:
['54.1757:-3.605', '61.5786:-2.5749', '67.9584:-15.0416', '104.4185:-15.9585']
使用列表理解很容易做到这一点。
>>> list = [[54.1757, 57.7807], [61.5786, 64.1535], [67.9584, 83.0], [104.4185, 120.377]]
>>>
>>> [ {x:y-x} for x, y in list ]
[{54.1757: 3.605000000000004}, {61.5786: 2.5748999999999924}, {67.9584: 15.041600000000003}, {104.4185: 15.9585}]
>>>