Python 如何比较数字子列表中的第一项,如果重复,则比较第二项并选择第二项最小的子列表?
我有一个带有数字的列表(列表长),我需要写一个列表(列表短),其中每个第一项(氨基酸序列号)只包含一个子列表,第二项最小(距离): 我用Python 3.6编写了这样的代码:Python 如何比较数字子列表中的第一项,如果重复,则比较第二项并选择第二项最小的子列表?,python,list,numbers,minimum,sublist,Python,List,Numbers,Minimum,Sublist,我有一个带有数字的列表(列表长),我需要写一个列表(列表短),其中每个第一项(氨基酸序列号)只包含一个子列表,第二项最小(距离): 我用Python 3.6编写了这样的代码: import itertools LIST_long = [['1', '50.9'], ['1', '9.0'], ['1', '10.2'], ['1', '2.0'], ['2', '50.1'], ['2', '8.8'],...] LIST_short = [] LIST_long = sorted(LIST_
import itertools
LIST_long = [['1', '50.9'], ['1', '9.0'], ['1', '10.2'], ['1', '2.0'], ['2', '50.1'], ['2', '8.8'],...]
LIST_short = []
LIST_long = sorted(LIST_long, key=lambda x:(x[0], x[1]))
for x, y in itertools.groupby(LIST_long, lambda x: x[0]):
LIST_short.append(list(y)[0])
print(LIST_short)
输出:
LIST_short = [['1', '10.2'], ['2', '50.1'],...]
而不是:
LIST_short = [['1', '2.0'], ['2', '8.8'], ...]
但是通过这种方式,添加了['1','10.2']
,而不是['1','2.0']
,因为据我所知,不是第二项的数字,而是逐位比较,1在2之前;8点之前5点等等
我将非常感谢在这个问题上给予的帮助。
期待您的建议。您可以使用dictionary获取结果,将子列表的第一项存储为dictionary的键,并相应地将第二项添加为列表中的值,然后获取列表的最小值,从而获得所需的结果
LIST_long = [['1', '50.9'], ['1', '9.0'], ['1', '10.2'], ['1', '2.0'], ['2', '50.1'], ['2', '8.8']]
from collections import defaultdict as dd
x = dd(list)
for i in LIST_long:
x[i[0]]+=[float(i[1])]
LIST_sort = []
for k, v in x.items():
LIST_sort.append([k, str(min(v))])
print(LIST_sort)
输出
[['1', '2.0'], ['2', '8.8']]
应采取以下措施:
LIST_long = [['1', '50.9'], ['1', '9.0'], ['1', '10.2'], ['1', '2.0'], ['2', '50.1'], ['2', '8.8']]
LIST_short = dict()
for id, value in LIST_long:
if id not in LIST_short or float(value) < float(LIST_short[id]):
LIST_short[id] = value
LIST_short = [[x, y] for x, y in LIST_short.items()]
LIST_long=[[1'、[50.9']、[1'、[9.0']、[1'、[10.2']、[1'、[2.0']、[2'、[50.1']、[2'、[8.8']
LIST_short=dict()
对于id,列表_long中的值:
如果id不在LIST_short或float(value)
您的代码工作正常,只需将x[1]
更改为float(x[1])
:
问题是,您将第二个元素作为字符串进行比较,而您本应将它们转换为
float
值进行比较。您的代码输出:LIST_short->[[[1]、[10.2]、[2]、[50.1']]
,这是错误的。非常感谢您的解释,现在它工作了:DThank you@sahasrara2 yours也是这个问题的很好的解决方案
LIST_long = [['1', '50.9'], ['1', '9.0'], ['1', '10.2'], ['1', '2.0'], ['2', '50.1'], ['2', '8.8']]
LIST_short = dict()
for id, value in LIST_long:
if id not in LIST_short or float(value) < float(LIST_short[id]):
LIST_short[id] = value
LIST_short = [[x, y] for x, y in LIST_short.items()]
import itertools
LIST_long = [['1', '50.9'], ['1', '9.0'], ['1', '10.2'], ['1', '2.0'], ['2', '50.1'], ['2', '8.8'],...]
LIST_short = []
LIST_long = sorted(LIST_long, key=lambda x:(x[0], float(x[1]))) # <<-- here
for x, y in itertools.groupby(LIST_long, lambda x: x[0]):
LIST_short.append(list(y)[0])
print(LIST_short)
>>> LIST_short
[['1', '2.0'], ['2', '8.8']]
>>>